views:

74

answers:

5

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

+3  A: 

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.

Ken Redler
+1 for "jQuery is not the answer to all questions..."
Hippo
+4  A: 

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);
}
Matthew Manela
+1  A: 

I had to do this for my own site, and I documented it here:
http://tech.bluesmoon.info/2010/01/handling-documentwrite-in-dynamic.html

bluesmoon
A: 

Yes, jQuery has a Ready method to deal with this: http://www.learningjquery.com/2006/09/introducing-document-ready

Carnotaurus
+1  A: 

You can use the DEFER attribute which will halt the loading and execution of the script until the rest of the page is loaded and ready:

<script src="script.js" type="text/javascript" defer="defer"></script>
LDJ
isn't that IE only?
bluesmoon