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

How to add callback after dynamically loading javascript file - Stack Overflow

programmeradmin0浏览0评论

I have the following function:

function require(url)
{
    var e = document.createElement("script");
    e.src = url;
    e.type="text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
}

Which allows to dynamically load javascript at runtime, and I need to add a callback after loading some new files

For example when I

require('className.js');

and just after this call

var a = new window[className];

file has not been loaded yet, so it generates an error.

I have the following function:

function require(url)
{
    var e = document.createElement("script");
    e.src = url;
    e.type="text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
}

Which allows to dynamically load javascript at runtime, and I need to add a callback after loading some new files

For example when I

require('className.js');

and just after this call

var a = new window[className];

file has not been loaded yet, so it generates an error.

Share Improve this question edited Sep 6, 2014 at 15:21 user4014548 asked Sep 6, 2014 at 14:04 Oleg PatrushevOleg Patrushev 631 silver badge4 bronze badges 1
  • 2 require(url, callback) { ... e.onload = callback } – eosterberg Commented Sep 6, 2014 at 14:07
Add a comment  | 

2 Answers 2

Reset to default 17

You can add an onLoad on the script element, but beware that on some older version of IE is a bit buggy.

Taking your code as a reference :

function require(url, callback) 
{
  var e = document.createElement("script");
  e.src = url;
  e.type="text/javascript";
  e.addEventListener('load', callback);
  document.getElementsByTagName("head")[0].appendChild(e);
}

require("some.js", function() { 
   // Do this and that
});

Further to Simone Gianni 's answer, in case you want to load a set of js files, plus run a callback at the end, where you want to ensure all files have loaded, you can do it recursively as follows:

function loadList(list, i, callback)
        {
            require(list[i], function()
            {
                if(i < list.length-1)
                {
                    loadList(list, i+1, callback);  
                }
                else
                {
                    callback();
                }
            });
        }

Call with:

    loadList(jsList, 0, function()
    {
        // code that applies after all URLs in jsList have loaded
    });
发布评论

评论列表(0)

  1. 暂无评论