最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to dynamically load scripts - Stack Overflow

programmeradmin0浏览0评论

I need to load some js files dynamically and sequentially(i.e. second script loads after load complete of first one, third after second and so on).

Question: how to detect when a script have been loaded? I have encountered problems with onload event - it not fires in IE8. After reading this, I tried to subscribe to onreadystatechange and wrote very ugly code for loading a script:

function loadScript(url, callback) {
        var isLoaded = false;
        var script = document.createElement('script');

        script.onreadystatechange = function () {
            if ((script.readyState == 'complete' || script.readyState == 'loaded') && !isLoaded) {
                if (callback) callback();
            }
        };
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', url);
        document.head.appendChild(script);
    };

Can you suggest better cross browser solution without such tricks?

UPD: Thanks for answers. What should I do if I need also to load jquery.js(for example, client have old version) :)?

I need to load some js files dynamically and sequentially(i.e. second script loads after load complete of first one, third after second and so on).

Question: how to detect when a script have been loaded? I have encountered problems with onload event - it not fires in IE8. After reading this, I tried to subscribe to onreadystatechange and wrote very ugly code for loading a script:

function loadScript(url, callback) {
        var isLoaded = false;
        var script = document.createElement('script');

        script.onreadystatechange = function () {
            if ((script.readyState == 'complete' || script.readyState == 'loaded') && !isLoaded) {
                if (callback) callback();
            }
        };
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', url);
        document.head.appendChild(script);
    };

Can you suggest better cross browser solution without such tricks?

UPD: Thanks for answers. What should I do if I need also to load jquery.js(for example, client have old version) :)?

Share Improve this question edited Oct 8, 2024 at 13:46 General Grievance 4,98837 gold badges37 silver badges55 bronze badges asked Aug 18, 2011 at 16:52 2xMax2xMax 1,7527 gold badges21 silver badges41 bronze badges 2
  • Regarding your update: why not include the library for loading your scripts (for example jQuery) like any other JavaScript file: <script src="jquery-1.5.1.min.js" type="text/javascript"></script> I don't see an easy way or the necessity to dynamically add the library you are going to use to load scripts dynamically. – Preli Commented Aug 18, 2011 at 18:35
  • @Preli, it will be embedded to another sites with one script and one div tags. – 2xMax Commented Aug 18, 2011 at 20:21
Add a comment  | 

3 Answers 3

Reset to default 10

I think what you need is jQuery.getScript

The function takes a URL and a success method with which you can chain loading of scripts and therefore load them sequentially:

jQuery.getScript( url, function() { 
  jQuery.getScript( url2, function() 
    {/*... all 2 scripts finished loading */}
  );
});

Here is my snippet for loading several scripts using jQuery.getScript();

function getScripts(inserts, callback)
{
    var nextInsert = inserts.shift();
    if (nextInsert != undefined)
    {
        console.log("calling"+nextInsert);
    jQuery.getScript(nextInsert, function(){ getScripts(inserts, callback); })
            .fail(function(jqxhr, settings, exception){alert("including "+nextInsert+" failed:\n" +exception)});
    }
    else
    {
        if (callback != undefined) callback();
    }
};

Usage:

var includes = [
    "js/script1.js",
    "js/script2.js",
    "js/script3.js"
];

getScripts(includes, function(){ /* typically a call to your init method comes here */; });

RequireJS:

... is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Says it is IE 6+, Firefox2 2+, Safari 3.2+, Chrome 3+ and Opera 10+ compatible.

发布评论

评论列表(0)

  1. 暂无评论