Loading ...

Load external JavaScript file dynamically | CodeAsp.Net

Load external JavaScript file dynamically

 /5
0 (0votes)

If you want to load external JavaScript file dynamically i.e via JavaScript code you can take help from the following code:

 

var loadJs= function (src, callback) {

    var s = document.createElement('script');

    document.getElementsByTagName('head')[0].appendChild(s);

    s.onload = function() {

        //callback if existent.

        if (typeof callback == "function") callback();

        callback = null;

    }

    s.onreadystatechange = function() {

        if (s.readyState == 4 || s.readyState == "complete") {

            if (typeof callback == "function") callback();

            callback = null; // Wipe callback, to prevent multiple calls.

        }

    }

    s.src = src;

};

 

Usage:

loadJs('https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js', function() {

    $('body').append('<p>Yahoo!</p>');

});

 

 

Comments (no comments yet)

Top Posts