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)
4 Answers 4
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.
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>
4 Comments
defer is better no? Because async will still block render whenever it gets loaded, so if path/script.js is small it won't really help that muchdefer is because according to MDN it hasn't been implemented by all major browsers. Although I'm having a hard time finding any other resources that verify that statement. Any idea about that?defer. I feel like most versions of IE probably don't though, you're righttry this :
function loadJs(url) {
var script = document.createElement('script');
script.src = url;
document.documentElement.firstChild.appendChild(script);
}
call the function by
loadJs("your-script.js");
to load JS after a set time,
setTimeout(function(){
loadJs("your-script.js");
},500);
you can also call it when all other components are loaded
window.onload = function() {
loadJs("your-script.js");
}
Comments
Keep your scripts right before </body> and put all of your JavaScript in a single file. Avoid loading several .js files. That's it.
Comments
Just like most analytic scripts, such as that from Google, they normally go bottom of the page so it doesn't interfere with the loading of the viewable contents. I don't think there is much to gain by timing exactly the loading vs sequencing the content/any resources loading. This is one of the many techniques, without knowing exactly what goes on in your code.
You can look into this article, https://varvy.com/pagespeed/defer-loading-javascript.html.
1 Comment
Explore related questions
See similar questions with these tags.
srcthe url to your file