Delay loading third-party javascript

Is there any method to delay loading third-party JavaScript files until the rest of the page finishes loading?

+4
source share
5 answers

You can connect to the onload event on the page, and after that you can dynamically insert file links.

For instance:

function loaded(){ var el = document.createElement("script"); el.src = "somefile.js"; el.type="text/javascript"; document.getElementsByTagName("head")[0].appendChild(el); } 
+8
source

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

If you want even content, such as images, to be loaded first, as well as cross-browser issues smoothed out for loading, the jQuery library simplifies this with $(window).load() and $.getScript() .

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

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

+3
source

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

To summarize, you have the following types of third-party scripts:

  • Those who play well with the page do not manipulate the DOM at all, do not create their own DOM nodes, or skip the DOM node identifier, to which all content will be sent, and wait until the DOM node appears in the DOM.

    You do not need to worry about these scenarios. You can safely load them asynchronously or load them after an onload or DOMContentReady fire. I personally prefer to download them asynchronously.

  • Those who use document.write to add content to the page. These scripts are annoying, but you deal with them with the aliasing document.write function, which is added to the innerHTML property of a particular DIV. My article talks about this.

  • Those that absolutely must be on the page before loading are usually scripts that measure the time it takes to launch onload. You will be asked to load these scripts using a regular script node, however, note that the script that measures onload is not really what delays loading. For this reason, I would say by loading such scripts asynchronously, but put the asynchronous loader at the top of the page (in the HEAD section). This makes it possible to boot before rebooting.

Also note one caveat, asynchronously added scripts will still block loading if they are added to the DOM before running onload, however they will not block the loading of any other content.

+2
source

You can use the DEFER attribute, which will stop 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> 
+1
source

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

0
source

All Articles