document.createElement(“script”) synchronously

前端 未结 11 2074
执念已碎
执念已碎 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:49

    function include(file){
    return new Promise(function(resolve, reject){
            var script = document.createElement('script');
            script.src = file;
            script.type ='text/javascript';
            script.defer = true;
            document.getElementsByTagName('head').item(0).appendChild(script);
    
            script.onload = function(){
            resolve()
            }
            script.onerror = function(){
              reject()
            }
          })
    
     /*I HAVE MODIFIED THIS TO  BE PROMISE-BASED 
       HOW TO USE THIS FUNCTION 
    
      include('js/somefile.js').then(function(){
      console.log('loaded');
      },function(){
      console.log('not loaded');
      })
      */
    }
    

提交回复
热议问题