Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS动态引入 #167

Open
louzhedong opened this issue Jul 24, 2019 · 0 comments
Open

JS动态引入 #167

louzhedong opened this issue Jul 24, 2019 · 0 comments

Comments

@louzhedong
Copy link
Owner

JS动态引入

当我们对性能有某些要求,希望JS脚本能在必要的时候才加载,我们就可能会用到动态JS引入

/**
 *
 *
 * @export
 * @param {*} url  JS的地址
 * @param {*} callback 加载完JS之后的回调函数,用于执行异步函数
 * @returns
 */
export function loadScript(url, callback) {
  // 通过闭包保存已经加载过的JS,防止重复加载
  const urlList = [];
  return function () {
    if (urlList.indexOf(url) > -1) {
      return;
    }
    callback = callback || function () { };
    const script = document.createElement('script');
    script.type = 'text/javascript';
    if (script.readyState) { //IE
      script.onreadystatechange = function () {
        if (script.readyState === "loaded" || script.readyState === "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function () {
        callback();
      };
    }
    script.src = url;
    document.body.appendChild(script);
    urlList.push(url);
  };
}

使用方法

loadScript("https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js")();
@louzhedong louzhedong changed the title JS动态加载 JS动态引入 Jul 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant