dom.js

作者: 泠泉 | 来源:发表于2019-04-24 09:55 被阅读0次
    export function remoteLoad (url, hasCallback) {
      return createScript(url)
    
      /**
       * 创建script
       * @param url
       * @returns {Promise}
       */
      function createScript (url) {
        var scriptElement = document.createElement('script')
        document.body.appendChild(scriptElement)
    
        var promise = new Promise((resolve, reject) => {
          scriptElement.addEventListener('load', e => {
            removeScript(scriptElement)
            if (!hasCallback) {
              resolve(e)
            }
          }, false)
    
          scriptElement.addEventListener('error', e => {
            removeScript(scriptElement)
            reject(e)
          }, false)
    
          if (hasCallback) {
            window.____callback____ = function () {
              resolve()
              window.____callback____ = null
            }
          }
        })
    
        if (hasCallback) {
          url += '&callback=____callback____'
        }
    
        scriptElement.src = url
    
        return promise
      }
    
      /**
       * 移除script标签
       * @param scriptElement script dom
       */
      function removeScript (scriptElement) {
        document.body.removeChild(scriptElement)
      }
    }
    
    

    相关文章

      网友评论

          本文标题:dom.js

          本文链接:https://www.haomeiwen.com/subject/sndwgqtx.html