Method encapsulation of dynamically loading js files

To summarize, the method of dynamically loading js files is encapsulated.

I will summarize this method later and use it directly.

/**
 * 加载js文件的方法封装
 */ 
class LoadScrpt {
    
    
  /**
   * 加载单个JS
   */
  static singleLoad(src) {
    
    
    return new Promise(function (resolve, reject) {
    
    
      let shouldAppend = false;
      let el = document.querySelector('script[src="' + src + '"]');
      if (!el) {
    
    
        el = document.createElement('script');
        el.type = 'text/javascript';
        el.async = true;
        el.src = src;
        shouldAppend = true;
      }else if (el.hasAttribute('data-loaded')) {
    
    
        resolve(el);
        return;
      }

      el.addEventListener('error', reject);
      el.addEventListener('abort', reject);
      el.addEventListener('load', function loadScriptHandler() {
    
    
        el.setAttribute('data-loaded', true);
        resolve(el);
      });

      if (shouldAppend) {
    
    
        document.head.appendChild(el);
      }
    });
  }

  /**
   * 加载js数组
   */
  static load(list) {
    
    
    let that = this;
    return new Promise(resolve => {
    
    
      function doLoad(url) {
    
    
        that.singleLoad(url).then(() => {
    
    
          if (list.length > 0) {
    
    
            doLoad(list.shift())
          } else {
    
    
            resolve()
          }
        })
      }

      if (list.length > 0) {
    
    
        doLoad(list.shift())
      } else {
    
    
        resolve()
      }
    })
  }

};

export default LoadScrpt;

Guess you like

Origin blog.csdn.net/xiaolinlife/article/details/134462522