Friday, May 10, 2024
71
rated 0 times [  77] [ 6]  / answers: 1 / hits: 25175  / 8 Years ago, sat, july 2, 2016, 12:00:00

It is very important my page load quickly. After loading I have a very javascript file that is not needed for anything until 10 seconds after page load. How can I best load the external sheet without slowing down initial page load?



setTimeout(function(){
//import Javascript
},500);


How would I import the javascript?
Would this even speed up page load?
Would some other technique work?



I'm not interested in analysis of whether this is worth it.



(note: I am actually doing this in the context of a chrome extension, I don't think it will matter dramatically)


More From » asynchronous

 Answers
22

Use the async attribute so that your script doesn't block the rendering of the page.



<script src=path/script.js async></script>



And if your really don't want the script execute after the page is loaded, then you can also wrap your code in window.onload. This way the downloading of the script won't block rendering of the page and your code won't be executed until after the page loads.



https://developers.google.com/web/fundamentals/performance/critical-rendering-path/adding-interactivity-with-javascript?hl=en






EDIT:



Another alternative that would be even better (if your browser supports it) would be defer, since it actually waits until the whole DOM is loaded, instead of async which only makes the loading of the script parallelized. Therefore:



<script src=path/script.js defer></script>


[#61545] Wednesday, June 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alli

Total Points: 409
Total Questions: 101
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
alli questions
Sat, Apr 23, 22, 00:00, 2 Years ago
Mon, May 18, 20, 00:00, 4 Years ago
Tue, Mar 24, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;