Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delay the loading of 3rd party javascript

Is there ANY method to delay the loading of 3rd party JavaScript files until the rest of the page has finished loading?

like image 239
Mayur Avatar asked Dec 07 '22 02:12

Mayur


2 Answers

You can attach to the onload event of page and once that fires you can dynamically insert the references to the files.

For example:

function loaded(){
   var el = document.createElement("script");
   el.src = "somefile.js";
   el.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(el);
}
like image 91
Matthew Manela Avatar answered Dec 17 '22 09:12

Matthew Manela


One simple way is to load them at the end of your html page.

If you want to ensure that even content like images have loaded first, plus get a bunch cross browser issues smoothed out to boot, the jQuery library makes this easy with $(window).load() and $.getScript().

$(window).load( function() {
    $.getScript('your_3rd_party-script.js');
});

jQuery is not the answer to all questions, but it does provide some nice abstractions. For example, you'll get automatic IE cache-busting (if you want it), and won't have to worry about the browser-specific issues of direct DOM-manipulation approaches.

like image 34
Ken Redler Avatar answered Dec 17 '22 11:12

Ken Redler