javascript 如何在具有冲突库的网站上正确包含 lodash/下划线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27561252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:38:18  来源:igfitidea点击:

How to correctly include lodash/underscore on website with conflicting libs?

javascripthtmlunderscore.jslodash

提问by grigoryvp

I have a website that includes a number of third-party js modules via scripttag. I need to add lodashor underscorefor my code, but if I simply add it from CDN like this:

我有一个网站,其中包含许多通过script标记的第三方 js 模块。我需要为我的代码添加lodashunderscore,但是如果我只是像这样从 CDN 添加它:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>

then badly written libs die terrible death because they expect _to be something else. I know that lodash/underscorehave something called "no conflict" mode, that requires jscode to be executed:

然后写得不好的库会死得很惨,因为他们希望_成为别的东西。我知道lodash/underscore有一种叫做“无冲突”模式的东西,它需要js执行代码:

var lodash = _.noConflict();

But this code needs to be executed somewhere, and it's really hard for me to ensure that it's executed before all badly written libs. Is it any simple way to include lodashalready in noconflict mode, so i don't need to search for a safe place to enable noconflict mode manually? like lodash.min.noconflict.js?

但是这段代码需要在某处执行,我真的很难确保它在所有写得不好的库之前执行。是否有任何简单的方法可以包含lodash在 noconflict 模式中,所以我不需要搜索一个安全的地方来手动启用 noconflict 模式?喜欢lodash.min.noconflict.js

回答by lossleader

As long as there are no relevant async scripts before the manual method, it should always work:

只要手动方法之前没有相关的异步脚本,它应该始终有效:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script>
_u = _.noConflict(); // lets call ourselves _u
</script>

It makes no difference if other scripts set/use _ before or after this. (lodash remembers the last setting of _ and restores it on the _.noConflict() call.)

其他脚本在此之前或之后设置/使用 _ 没有区别。(lodash 记住 _ 的最后一个设置并在 _.noConflict() 调用中恢复它。)

But if scripts before this are async there is always a possibility that they are allowed to execute between these two scripts. You would have to either use AMD or combine the manual setting into the same script as lodash to avoid races with async scripts.

但是,如果在此之前的脚本是异步的,则总是有可能允许它们在这两个脚本之间执行。您必须使用 AMD 或将手动设置组合到与 lodash 相同的脚本中,以避免与异步脚本发生竞争。

回答by Cedriga

The latest CDN version is 4.17.15 :)

最新的 CDN 版本是 4.17.15 :)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"> </script>
<script>
_u = _.noConflict();
</script>