vue组件引入外部js同时获取变量,解决重复引入

vue组件引入外部js同时获取变量

引入文件支持加载成功回调,支持通过字符串变量名获取js文件的变量

/**
 * 引入js文件 并且获取变量
 * @param src js路径
 * @param variableName 需要获取的变量名
 * @param callback
 */
export const importJs = (src, variableName = '', callback = '') => {
  if (!isInclude(src)) { // 避免重复引入
    const script = document.createElement('script')
    script.type = 'text/JavaScript'
    script.src = src
    document.body.appendChild(script)
    if (typeof callback === 'function') {
      script.onload = script.onreadystatechange = function() {
        if (!script.readyState || /loaded|complete/.test(script.readyState)) {
          script.onload = script.onreadystatechange = null // 避免重复触发
          const fn = new Function('return ' + variableName)
          callback(variableName !== '' ? fn() : '')
        }
      }
    }
  } else if (typeof callback === 'function') {
    const fn = new Function('return ' + variableName)
    callback(variableName !== '' ? fn() : '')
  }
}
// 是否引入资源文件
function isInclude(name) {
  const js = /js$/i.test(name)
  const es = document.getElementsByTagName(js ? 'script' : 'link')
  for (let i = 0; i < es.length; i++) {
    if (es[i][js ? 'src' : 'href'].indexOf(name) !== -1) return true
  }
  return false
}

你可能感兴趣的:(vue,javascript,vue.js,前端)