Vue动态引入JS文件

引入前请先:

npm install jquery

正式代码:

//动态引入JS文件
function loadJavaScript(src, callback) {
        let script_list=$("script[src]").toArray().map(ret=>{
            return ret.src
        })
        if(script_list.indexOf(src)===-1){
            var script = document.createElement('script'),
                head = document.getElementsByTagName('head')[0];
            script.type = 'text/javascript';
            script.charset = 'UTF-8';
            script.src = src;
            if (script.addEventListener) {
                script.addEventListener('load', function () {
                    setTimeout(function () {
                        callback();
                    },500);
                }, false);
            } else if (script.attachEvent) {
                script.attachEvent('onreadystatechange', function () {
                    var target = window.event.srcElement;
                    if (target.readyState == 'loaded') {
                        setTimeout(function () {
                            callback();
                        },500);
                    }
                });
            }
            head.appendChild(script);
        }else {
            callback();
        }
}

不需要引入JQ的

  //动态引入JS文件
  function loadJavaScript(src, callback) {
    let script_list=[]
    document.querySelectorAll("script[src]").forEach(ret=>{  script_list.push(ret.src) })
    if(script_list.indexOf(src)===-1){
      var script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0];
      script.type = 'text/javascript';
      script.charset = 'UTF-8';
      script.src = src;
      if (script.addEventListener) {
        script.addEventListener('load', function () {
          setTimeout(function () {
            callback();
          },500);
        }, false);
      } else if (script.attachEvent) {
        script.attachEvent('onreadystatechange', function () {
          var target = window.event.srcElement;
          if (target.readyState == 'loaded') {
            setTimeout(function () {
              callback();
            },500);
          }
        });
      }
      head.appendChild(script);
    }else {
      callback();
    }
  }

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