delay the loading of 3rd party javascript
I开发者_如何学Gos there ANY method to delay the loading of 3rd party JavaScript files until the rest of the page has finished loading?
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);
}
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.
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
To summarize, you have the following types of third party scripts to deal with:
Those that play nicely with the page, either do not manipulate the DOM at all, create their own DOM nodes, or let you pass in the id of a DOM node within which all its content will go, and waits until that DOM node shows up in the DOM.
You do not need to worry about these scripts. You can safely load them asynchronously, or load them after the onload or DOMContentReady events fire. I personally prefer loading them asynchronously.
Those that use
document.write
to add content to the page. These scripts are annoying, but you deal with them by aliasingdocument.write
to a function that appends to theinnerHTML
property of a specific DIV. My article talks about this.Those that absolutely must be on the page before onload fires, typically scripts that measure the time it takes for onload to fire. You'll be asked to load these scripts using a regular script node, however, consider that a script that measures onload should not actually be the thing that delays onload. For this reason, I'd say load such scripts asynchronously, but put the asynchronous loader at the top of your page (in the HEAD) section. This gives it a chance to load before onload fires.
Also, note one caveat, asynchronously added scripts will still block onload if they were added to the DOM before onload fired, however they won't block any other content from loading.
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>
Yes, jQuery has a Ready method to deal with this: http://www.learningjquery.com/2006/09/introducing-document-ready
精彩评论