3

Webpack 支持符合ECMAScript动态导入提议的import()语法。此语法使用 Promise 异步加载模块。

问题是,一旦特定模块被加载,承诺就会被解决,而无需等待模块的依赖项加载(可以是任何类型的资产,包括 JS 和 CSS)。

示例代码:

import('./myModule.js').then(myModule => {
    myModule.sayHello(); // This will be called before someCSS.css has been loaded
});

我的模块.js

import './someCSS.css'; // <-- I need to know when this is loaded (there can be more than one asset)

export default class myModule {
    sayHello() {
        alert('Hello!');
    }
}

如何检测模块和所有相关资产的加载时间?类似于onload异步资产的事件?

4

2 回答 2

0

该方法返回 Promise,它允许您确定脚本是否已加载或加载时发生错误(例如):

// utils.js
function insertJs({src, isModule, async, defer}) {
    const script = document.createElement('script');

    if(isModule){
      script.type = 'module';
    } else{
      script.type = 'application/javascript';
    }
    if(async){
      script.setAttribute('async', '');
    }
    if(defer){
      script.setAttribute('defer', '');
    }

    document.head.appendChild(script);

    return new Promise((success, error) => {
        script.onload = success;
        script.onerror = error;
        script.src = src;// start loading the script
    });
}

export {insertJs};

//An example of its use:

import {insertJs} from './utils.js'

// The inserted node will be:
// <script type="module" src="js/module-to-be-inserted.js"></script>
const src = './module-to-be-inserted.js';

insertJs({
  src,
  isModule: true,
  async: true
})
    .then(
        () => {
            alert(`Script "${src}" is successfully executed`);
        },
        (err) => {
            alert(`An error occured during the script "${src}" loading: ${err}`);
        }
    );
// module-to-be-inserted.js
alert('I\'m executed');
于 2017-08-29T12:10:43.530 回答
0

可以document.styleSheets用来检查所有样式表何时已加载。只有在加载样式表后,CSSStyleSheet对象才会包含一个属性,因此您可以创建一个对其进行检查的 Promise:cssRules

export function awaitStylesheets() {
    let interval;
    return new Promise(resolve => {
        interval = setInterval(() => {
            for (let i = 0; i < document.styleSheets.length; i++) {
                // A stylesheet is loaded when its object has a 'cssRules' property
                if (typeof document.styleSheets[i].cssRules === 'undefined') {
                    return;
                }
            }

            // Only reached when all stylesheets have been loaded
            clearInterval(interval);
            resolve();
        }, 10);
    });
}
于 2017-08-30T21:43:37.480 回答