懒加载引用第三方js,css文件

懒加载引用第三方js,css文件

Arthur
2023-11-27 / 0 评论 / 56 阅读 / 正在检测是否收录...
export const loadResourceInHead = (src) => {
    return new Promise((resolve, reject) => {
        if (!src) {
            reject('The src cannot be empty!');
            return;
        }

        if (src.startsWith('/')) {
            // src = endpoints.ui + src;
        }
        let suffix = src.substring(src.lastIndexOf('.') + 1);
        if (suffix.indexOf('?') >= 0) {
            suffix = suffix.substring(0, suffix.indexOf('?'));
            // eslint-disable-next-line no-undef
            src += '&hash=' + __webpack_hash__;
        } else {
            // eslint-disable-next-line no-undef
            src += '?' + __webpack_hash__;
        }
        const isScript = suffix.toLowerCase() === 'js';

        const tagName = isScript ? 'script' : 'link';
        const loadedTag = document.head.querySelector(tagName + "[" + (isScript ? "src" : "href") + "^='" + src + "']");
        if (loadedTag) {
            if (loadedTag.ready) {
                resolve();
                return;
            }
            const oldOnload = loadedTag.onload;
            loadedTag.onload = function (res) {
                oldOnload && oldOnload();
                resolve(res);
            };
            return;
        }

        const tag = document.createElement(tagName);
        tag.type = isScript ? 'text/javascript' : 'text/css';
        tag[isScript ? 'src' : 'href'] = src;
        if (!isScript) {
            tag.rel = 'stylesheet';
        }
        document.head.appendChild(tag);
        $$.loading(true);
        tag.onload = function (res) {
            $$.loading(false);
            tag.ready = true;
            resolve(res);
        };

        tag.onerror = function (error) {
            $$.loading(false);
            reject(error);
        };
    });
};

用法:

 window.promiseAll(
            utils.loadResourceInHead("ckeditor.js"),
            utils.loadResourceInHead("math.js"),
            utils.loadResourceInHead("music.js"),
        ).then(() => {
            if (!RichEditor.loaded) {
                RichEditor.loaded = true;
            }
            this.setState({ loaded: true });
        });
0
如果你觉得文章还不错,可以请我喝杯咖啡啊哈哈哈
wechat alipay

评论 (0)

取消