简体   繁体   English

在纯JS中加载JS文件后的回调

[英]Callback after loading JS file in pure JS

I've loaded Modernizr with pure JS. 我已经用纯JS加载了Modernizr。

var modernizr = document.createElement('script');
modernizr.src = 'http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.min.js';
modernizr.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(modernizr);

Now i want to use Modernizr.load to include more JS files. 现在,我想使用Modernizr.load包含更多JS文件。 Is there a callback function when Modernizr is loaded? 加载Modernizr时是否有回调函数?

Add the onload and onreadystatechange events to the object. onloadonreadystatechange事件添加到对象。 With as much as possible browser support and ie hacks it looks like this: 通过尽可能多的浏览器支持和黑客攻击,它看起来像这样:

modernizr.onload = modernizr.onreadystatechange = function () {
    if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
        done = true;

        // Handle memory leak in IE
        modernizr.onload = modernizr.onreadystatechange = null;
        if (head && modernizr.parentNode) {
            head.removeChild(modernizr);
        }

        callback();
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM