vue 动态加载第三方js回调事件

时间:2024-03-07 13:16:24

vue页面,引入第三方js

需要在加载完远程js后执行初始化操作。

// 取出Promise中的resolve方法,在sdk onload方法中调用
let isLoad;
const loadPromise = new Promise((resolve, reject) => {
  isLoad = resolve;
});

// 创建script标签,添加到body
const sdk = document.createElement(\'script\');
sdk.type = \'text/javascript\';
sdk.src = \'https://www.xxx.com/sdk.js\';

sdk.onload = () => {
  isLoad();
};

document.body.appendChild(sdk);

// vue 代码
export default {
  mounted() {
    loadPromise.then(() => {
      console.log(\'sdk加载完成\');
      // do something
    });
  }
};

 

 更新:封装了动态加载js方法,加载多个js方法

// 动态加载js
function dynamicLoadScript(src) {
  return new Promise((resolve, reject) => {
    const script = document.createElement(\'script\');
    script.src = src;

    script.onload = function () {
      resolve(src);
    };
    script.onerror = function () {
      reject(new Error(\'Failed to load \' + src), script);
    };

    document.body.appendChild(script);
  });
}

// 动态加载多条js
function loadScripts(urls) {
  return Promise.all(urls.map((url) => dynamicLoadScript(url)));
}

const hasLoad = new Promise((resolve) => {
  loadScripts([
    \'https:/xxx.js\',
    \'https:/xxx.js\',
    \'https:/xxx.js\',
  ]).then(() => {
    resolve();
  });
});

export default {
  name: \'component\',
  data() {
    return {};
  },
  beforeCreate() { },
  mounted() {
    hasLoad.then(() => {
      console.log(\'加载完成\');
      // do something
    });
  }
};