lazy loading javascript

  1. Uses ajax to load the script. More specifically it uses XHR to load some js and have it available to the browser. No blocking is done. It does still enforce the same origin policy.
  2. Modifies the header to inject a new .js file by creating <script/> element. This also doesn't block the browser on page load.
  3. Does the same thing as #2 but it seems to support an array of scripts. It also sets async to true which causes no blocking. The for loop is just more confusing because it creates a lot more anonymous methods.

  1. Seems to retrieves the script with a XmlHttpRequest and eval() it. This won't work if the script is not hosted on the same protocol / domain / port.

  2. and 3. seems to both do the same thing: they create a <script src="the script url"></script> element, bind onload events on it and insert it on the page. The script is executed by the browser once it is loaded, and the onload event is fired.


  1. Gets the script via ajax, and eval()'s the contents
  2. Insert a script element into the head element and report back when it has loaded
  3. Same as (2) but accept and array of script urls, and is way more complexly written

(2) and (3) both use the onreadystatechange hook, which may not be compatible with older browsers (for instance, Firefox 3.x and below doesn't support it).

(1) is probably the most robust, compatibility-wise, since it just requires XHR. But if you get errors in the code you load that way, the browser's console may not be very helpful, as the error just occurred in "eval'd code" and not in a specific file/line. That said, lazy loading is typically an optimization thing, so you can just include the scripts normally, or with any of the other 2 methods, while debugging.