When is a JavaScript include ready?

October 23rd, 2006. Tagged: JavaScript

This is a follow up to my article (the most popular on my blog based on the comments) about the JavaScript includes, the technique to include new .js files after the page is loaded, by using DOM to create a new script tag. The problem that is discussed in the comments is how to find out when/if the new script was actually downloaded. Here's a solution (IE only!).

Today I came accross an article on MSDN, written back in 1998 where they talk about readyState property of an inline JavaScript. So I decided to try it in conjunction with my JS includes. It worked! The solution is IE-only, but probably there is something similar for Firefox. Please post a comment if you know one.

The idea is that after a new DOM element (a script tag) is created, you can have access to the readyState property of the element. If it says "complete", then the new script is included and it's OK to call functions from it. If you want to "listen" when the script download will be completed, you can attach an listener to the onreadystatechange event, just like with XMLHttpRequests.

Here's an example:

var js;
function include_js(file) {
    var html_doc = document.getElementsByTagName('head').item(0);
    js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', file);
    // alert state change
    js.onreadystatechange = function () {
        if (js.readyState == 'complete') {
            // safe to call a function
            // found in the new script
    return false;

This also works if you decide to include new CSS files on the fly. If you want to know in your javascript when the CSS is downloaded, you can do the same check.

Here's a demo that includes a CSS and alert()s onreadystatechange and also includes a JS, alerts the state change and when "complete", calls a function from the newly inlcluded script.

This solution to the problem "When is my include loaded?" is perfect, if you ask me, very clean and simple. The problem is it's IE-only, but the good news is that FF won't give you an error, it will just work as if the extra code was not there, simply because FF won't fire an onreadystatechange event.

2006-10-25 update: Thanks to the comments, the cross-browser way is here.

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov