热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何规避RequireJS加载全局模块?

如何解决《如何规避RequireJS加载全局模块?》经验,应该怎么办?

我正在尝试从书签中加载JS文件.JS文件有这个包装模块的JS:

(function (root, factory) {
    if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else {
        // Browser globals
        root.moduleGlobal = factory();
    }
}(this, function factory() {
    // module script is in here

    return moduleGlobal;
}));

因此,如果网页使用RequireJS,则脚本在加载时不会导出全局.为了解决这个问题我暂时设置definenull,加载脚本,然后重置define为其原始值:

function loadScript(url, cb) {
    var s = document.createElement('script');
    s.src = url;
    s.defer = true;
    var avoidRequireJS = typeof define === 'function' && define.amd;
    if (avoidRequireJS) {
        var defineTmp = define;
        define = null;
    }
    s.Onload= function() {
        if (avoidRequireJS) define = defineTmp;
        cb();
    };
    document.body.appendChild(s);
}

这是有效的,但在我看来,当应用程序的其他部分可能依赖于它时,更改全局变量可能会有问题.有没有更好的方法来解决这个问题?


推荐阅读
author-avatar
手机用户2502907453
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有