Reputation: 923
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)
Upvotes: 12
Views: 30409
Reputation: 1318
try 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");
}
Upvotes: 10
Reputation: 349
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>
Upvotes: 16
Reputation: 265
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.
Upvotes: 0
Reputation: 18585
Keep your scripts right before </body>
and put all of your JavaScript in a single file. Avoid loading several .js files. That's it.
Upvotes: 0