Home > JavaScript > JavaScript: How to add a script-tag dynamically

JavaScript: How to add a script-tag dynamically

     Sometimes it’s necessary to add a JavaScript to a page dynamically. For example, if you have a huge and rarely used JavaScript, it’s unreasonable to load it jointly with the page. The more wisely to load it on demand, when it’s really needed. It’s, so called, lazy loading. One of the ways to achieve it is presented below:

// url      - a string-based url of js-file
// callback - reference to a user-defined method, which will be called when loading is finished
function AddScript(url, callback) {
    var script   = document.createElement('script');
    script.src   = url;
    script.type  = 'text/javascript';
    script.defer = false;

    if (typeof callback != "undefined" && callback != null) {
    
        // IE only, connect to event, which fires when JavaScript is loaded
        script.onreadystatechange = function() {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                this.onreadystatechange = this.onload = null; // prevent duplicate calls                        
                callback();
            }
        }

        // FireFox and others, connect to event, which fires when JavaScript is loaded
        script.onload = function() {
            this.onreadystatechange = this.onload = null; // prevent duplicate calls                    
            callback();
        };
    }
    
    var head = document.getElementsByTagName('head').item(0);
    head.appendChild(script);
}

The method AddScript accepts the url of js-file, the contents of which should be loaded, and callback – an user-defined method that will be called when the load is complete.

Taking into account that browsers may (and I believe they do that) load JavaScript asynchronously, the callback is very useful if you need to do some actions based on just loaded JavaScript. In other words, your actions precisely will not be performed before loading has finished or even started, or your actions could cause an error on the page.

Usage:

AddScript("jquery-1.6.2.js",
    function() {
        alert($(document).attr('title'));
    });

ps The method was tested in FireFox and Internet Explorer

Related posts:
 
Categories: JavaScript Tags:
  1. No comments yet.
  1. No trackbacks yet.