Lazy Loading Asyncronous Javascript
Update: This is no longer the best way to load scripts. Use a script tag with async and defer set instead.
Like many of you might know, I'm working on a site called Kundo with a couple of friends. It's kinda like a Swedish version of Getsatisfaction, which means we have a javascript snippet that people add to their site to get feedback functionality. Cut-and-paste instead of writing the code yourself. Simple.
The problem is, how do you load an external javascript with minimal impact on your customer's sites? Here are my requirements:
- Small. I don't want a big mess for them to include on their sites. 10-15 lines, tops.
- Stand-alone. The environment is unknown, so we can't rely on any external dependencies, like javascript libraries.
- Cross-browser. I have no idea what browsers my customer's customers have, so I can't do anything modern or fancy that isn't backwards compatible. I assume at least IE6 and up though.
- Asynchronous download. The download of my script should not block the download of any script on their sites.
- Lazy Loading. If my site is temporarily slow, I don't want to block the onload event from triggering until after our site responds.
- Preserve events. Any events used should not override any events on the customer's site. Minimal impact, like I said.
- Don't pollute namespace. Global variables should be avoided, since they could conflict with existing javascript.
Note: I did not make all of this up myself. Lots of people did, I'm just writing it down for you. Thanks: Jonatan, Steven, Peter, and Linus.
Script tag#
<script src="http://yourdomain.com/script.js"></script>
While being the stand-alone, cross-browser, and the shortest piece of code possible; it doesn't download asynchronously and doesn't lazy load. Fail.
Screenshot from Firebug's net console: The script (set to load in 2 seconds) blocks the download of the big image (added after the above script tag, and used throughout this article as a test). Onload event (the red line) triggers after 2.46 seconds.
Async pattern (A script tag written with javascript)#
Steve Souders, the web performance guru, has compiled a decision tree over different ways to achieve non-blocking downloads. Have a look at that graph.
Since we're on a different domain, and only have one script (order doesn't matter), the solution is given: We should create a script tag with inline javascript, and append it to the document. Voila! Non-blocking download!
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://yourdomain.com/script.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
})();
Note: async
is a HTML5 attribute, doing exactly what we're trying to simulate with our hack, so it's added for good measure. Also, wrapping the code in an anonymous function prevents any variables to leak out to the rest of the document.
This is a pattern that is getting more and more popular nowadays, especially since Google Analytics uses it. But there's an important distinction here: The above snipped blocks onload from triggering until the referenced script is fully loaded. Fail.
Update 2010-09-01: Steve Souders adds that the above is only true for Firefox, Chrome, and Safari, but not IE and Opera. So for a IE-only site, this might be the best method.
Screenshot from Firebug's net console: The script (set to load in 2 seconds) downloads in parallell with the big image. Onload event (the red line) triggers after 2.02 seconds.
Lazy load pattern (Async pattern triggered onload)#
So, how to you make sure you don't block onload? Well, you wrap your code inside a function that's called on load. When the onload event triggers, you know you haven't blocked it.
window.onload = function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://yourdomain.com/script.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
This works, but it overrides the onload event of the site that uses the script. This could be OK in some cases, where you have control over the site referencing the script, but I need to cater for that. Fail.
Unobtrusive lazy load pattern#
The logical solution to the above problem is to use an incarnation of addEvent. addEvent is simply a common name for an cross browser way to take the current function tied to onload, add it to a queue, add your function to the queue, and tie the queue to the onload event. So which version of addEvent should we use?
There's been competitions for writing a short and compact version of addEvent, and the winner of that competition was John Resig, with this little beauty:
function addEvent(obj, type, fn) {
if (obj.attachEvent) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn](window.event);}
obj.attachEvent('on'+type, obj[type+fn]);
} else
obj.addEventListener(type, fn, false);
}
Note: This is unsafe code, since it relies on serializing a function to a string, something that Opera mobile browsers have disabled.
Thing is, we don't need all that generic event stuff, we're only dealing with onload here. So if we first replace the type attribute with hardcoded 'load', replace obj with 'window', and remove the fix for making 'this' work in IE, we've got four lines of code left. Let's combine this with the above lazy load pattern:
(function() {
function async_load(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://yourdomain.com/script.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
if (window.attachEvent)
window.attachEvent('onload', async_load);
else
window.addEventListener('load', async_load, false);
})();
This is exactly what we're looking for here. Finally!
Screenshot from Firebug's net console: The script (set to load in 2 seconds) downloads after the onload event has triggered. Onload event (the red line) triggers after 0.41 seconds.
And that wraps up this article: Different tactics works for different scenarios, and only understanding them all makes you capable of picking the right one for your problem. As always, I'm waiting for your feedback in the comments. Thanks for reading!
Comments
By: Dean Higginbotham (#1)
Totally bookmarking this to give it a thorough read-through! I've been looking for this info for a long time and everywhere else it's a mish-mash of "do this!", "no, do this!", "no, this is the right way!", etc...
By: Morgan Cheng (#2)
In my experience, since jQuery is used, most actions can be done at 'DomContentLoaded' event instead of 'load' event. So, it really doesn't matter async loaded javscript delay 'load' event. Is there any specific requirement that the javascript should not delay 'load'?
By: Emil Stenström (#3)
By: Emil Stenström (#4)
@Morgan: I have no idea what techniques my customers are using, so I don't know if they use jQuery, prototype or just native javascripts relying on the onloaded event. Would be great if I knew that all of them used a library that triggered their scripts on domcontentloaded, but I can't know that for sure.
By: jarvklo (#5)
Thanks for sharing!
By: Kristoffer Nolgren (#6)
By: Emil Stenström (#7)
@Kristoffer: Som du märker så jobbar vi hårt på att få upp hastigheten :) Det kommer mera framöver!
By: Kristoffer Nolgren (#8)
En tanke jag haft, som ni kanske också har övervägt är att erbjuda en serverside-lösning, i alla fall för själva knappen, som ju är vad de allra flesta av användarna upplever.
Egentligen är det kanske inte så jättemycket som ni faktiskt behöver koda, bara att erkänna det som "good practice" att inte ladda knappen via javascriptet. Vi har valt att inte göra det för att undvika att nått pajjar vid uppdateringar och så.
By: Mathias (#9)
Well, you could optimize this snippet even more if you wanted to. For example, why are you setting
s.type = 'text/javascript';
? It’s completely unnecessary. You could also cache the string'script'
and a store a reference todocument
in a variable, and re-use those to save even more bytes. (This is exactly what’s going on in my optimized asynchronous Google Analytics snippet.)Also, if you don't want to pollute the global namespace, you should probably prepend
x = document.getElementsByTagName('script')[0];
withvar
.The
if
check at the end can be rewritten as follows:window.attachEvent ? window.attachEvent('onload', async_load) : window.addEventListener('load', async_load, false);
By: Emil Stenström (#10)
By: Emil Stenström (#11)
By: Roland Bouman (#12)
thanks for sharing :)
Roland.
By: Aki Kärkkäinen (#13)
By: Wayne State Web Communications Blog » Blog Archive » [Friday Links] The Monday Edition (#14)
By: Bryan (#15)
x
without thevar
keyword, does that not expose it to any external methods? I thought that you needed to usevar
to keep the scope local to that function.By: Emil Stenström (#16)
By: Rizo (#17)
By: Robin Jakobsson (#18)
Valuable lessons,
thanks!
By: Wayne State Web Communications Blog » Blog Archive » [Friday Links] The Startup Weekend Edition (#19)
By: CodeMyConcept (#20)
Thank you!
By: Linus G Thiel (#21)
By: Stephan Schubert (#22)
By: Josh (#23)
By: Riyad Kalla (#24)
Brilliant writeup. I didn't expect you to walk through all past-and-present options for async loading... this is going in my JS quick-reference toolbox of bookmarks. Bravo dude.
By: Emil Stenström (#25)
By: Steve (#26)
I've never thought about loading external scripts much, I am just getting in to Javascript and this has helped me out lots.
Thanks :)
By: Ashish (#27)
It's nice post, We have already tried this in few of our website projects and it works flawless.
Thanks :-)
By: Roi (#28)
Thank you!
By: onequad (#29)
By: Steve Souders (#30)
Under Script Tag you have script type="", but I think you mean script src="".
Async Pattern (dynamically added SCRIPT element) is rejected because it blocks the onload event. Although this is true in Firefox, Chrome, and Safari, it's not true in IE and Opera. Also, I haven't tested this recently with growing support for the SCRIPT ASYNC attribute (altho the HTML5 spec says onload should be blocked, so I'm not optimistic).
Certainly waiting until after the load event has fired avoids blocking the page, but if a widget's content is valuable to the page it's important to load earlier. Note that 5-15% of pages don't reach the load event - users click through before that happens.
By: Emil Stenström (#31)
About onload: Yeah, it's unfortunate to have to wait that long. As a supplier of an external service, we feel that the customers own site always have to be prioritized above our script. So blocking their onload event is not something that we think is acceptable.
I can only wish that all ad suppliers did that same.
By: Aaron Peters (#32)
Have you considered dynamically creating an iframe?
I know the Meebo guys went down this path and are very happy with the result, although it wasn't easy to get this to work cross-browser.
http://blog.meebo.com/?p=2633
By: Gavin (#33)
the perfect way to include 3rd party code without affecting page load
By: Martin (#34)
I'm using the Async pattern but I'd changed the closure statment by a setTimeout call. It's working perfect on IE and Opera.
By: Enrico (#35)
But I encounter a problem with browser caching and the version with the onload event. The browser does then no longer recognize any changes in the loaded javascript.
I also opened a question at stackoverflow:
http://stackoverflow.com/questions/3674830/caching-problem-with-asynchronous-javascript-loading-with-onload-event
Maybe somebody knows a solution to this?
By: Emil Stenström (#36)
By: Emil Stenström (#37)
By: Emil Stenström (#38)
By: Alexander (#39)
By: ??????????? ???????? ???????? ? HTML ???????? « ????????? (#40)
By: Nicolas (#41)
By: Damien P. (#42)
By: G (#43)
Can you elaborate a bit on what the best-practices are for the script that gets inserted (http://yourdomain.com/script.js in your example code).
What should be in there? I tried to look into your http://static.kundo.se/embed.js code but that is minified.
Thanks in advance!
By: Peter (#44)
I have one question. Is it possible to have fallback scripts for when a external script fails to load? For example, I would like to use Google's version of jQuery since that will already be cached by many users, but I need a local fallback version in case Google is not available (Google is blocked in several countries). However, how do I check if an asynchronous scripts is properly loaded?
Thanks anyway for the great explanation!
By: Emil Stenström (#45)
What most people do it first try to load the jQuery script, and then check if the global object "jQuery" is defined, otherwise load it another way. Here's a thread from StackOverflow with lots of good answers: http://stackoverflow.com/questions/1014203/
By: DealsKing (#46)