使用requires预加载填充库



我正在使用requirejs创建一个wirejs应用程序。对于IE 8,我使用polyfills: cujo/poly js库,并要求在wirejs加载之前预加载该库。

如果我使用curl作为AMD加载程序,根据文档,我有以下选项可用:

curl({ preloads: [ "poly" ] });

适合我的是:

// in index.html
<script data-main="js/app" src="js/lib/require.js"></script>
// in js/app.js
define(function(){
   // set configuration options
   requirejs.config({// set config with paths});
   // require the library and HOPE it will load before
   // everything else!
   require(['poly']);
});

本文档建议使用shim config实现此目的。然而,我一直不知道怎么做到的。我尝试过的一些事情:

// DID NOT WORK!!
requirejs.config({
....
"shim": {
   "poly": {
     "exports": "poly"
    }
 }
});

有更好的方法来处理这个问题吗?

感谢任何帮助!谢谢你的时间!

我确实将RequireJS与多边形一起使用,但我不使用RequireJS来加载它们。polyfill的目标是使一个浏览器缺乏功能X看起来好像它实际上有功能X。我更喜欢这样一种设置,其中所有我运行的代码(除了polyfills本身)与已经加载的polyfills一起运行,这样代码就可以用相同的功能集运行,无论什么浏览器运行代码。所以我希望我的多边形也在RequireJS之前加载。

但是如果我们忽略这个首选项,RequireJS可以用来加载填充吗?是的,但是RequireJS不会让它变得容易。没有什么简单的方法可以告诉RequireJS"在加载任何其他之前必须加载这个代码体",这就是你想要的填充。你要做的是手动调用require,这样你的多边形首先加载。你的index.html可以是这样的:

<script>
    require = {
       // Your config.
       //
       // Setting a global require before loading RequireJS is one way to give it
       // a config.
    };
</script>
<script src="js/lib/require.js"></script>
<script>
    // No data-main above...
    //
    // This double require ensures that the polyfills are loaded first.
    require(["poly"], function () {
        require(["js/app"]);
    });
</script>

js/app.js变为:

define(function(){
    // whatever...
});

在一个大型应用程序中,可能有多个入口点,而不是js/app,你必须使用以上的双重要求,每次你想从外部的RequireJS模块加载一个模块,以确保polyfills首先加载。

我遇到了同样的问题,我的解决方案是让Require.js加载多边形作为我的依赖项。你可以在这个要点中看到我是如何结合Conditioner.js解决它的,但是没有它的解决方案是一样的。

我选择了检测加载多边形的功能,这样新浏览器就不会产生不必要的请求。特征检测使这个特定的解决方案更加优越。

在你的index.html:

<script src="/js/require.js" data-main="/js/main"></script>

在文件/js/main.js:

var _polyfills = [];
if (!('classList' in document.documentElement)) {
    _polyfills.push('polyfills/classList');
}
// ... more feature detects & polyfills ...
require(['bootstrap'].concat(_polyfills), function(bootstrap) {
    bootstrap.run(); // Bootstrap your app here!
});

最新更新