document.createElement(“script”) synchronously

前端 未结 11 2337
执念已碎
执念已碎 2020-11-22 12:56

Is it possible to call in a .js file synchronously and then use it immediately afterward?



        
11条回答
  •  佛祖请我去吃肉
    2020-11-22 13:52

    This is way late but for future reference to anyone who'd like to do this, you can use the following:

    function require(file,callback){
        var head=document.getElementsByTagName("head")[0];
        var script=document.createElement('script');
        script.src=file;
        script.type='text/javascript';
        //real browsers
        script.onload=callback;
        //Internet explorer
        script.onreadystatechange = function() {
            if (this.readyState == 'complete') {
                callback();
            }
        }
        head.appendChild(script);
    }
    

    I did a short blog post on it some time ago http://crlog.info/2011/10/06/dynamically-requireinclude-a-javascript-file-into-a-page-and-be-notified-when-its-loaded/

提交回复
热议问题