简体   繁体   中英

Callback after loading JS file in pure JS

I've loaded Modernizr with pure JS.

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. Is there a callback function when Modernizr is loaded?

Add the onload and onreadystatechange events to the object. 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();
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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