简体   繁体   English

如何防止 object 和 function 名称在不同的.js 文件中发生冲突

[英]How do I prevent conflict between object and function names in different .js files

I just added google analytics to my site.我刚刚将谷歌分析添加到我的网站。 About 25% of the time when it loads, i get the following error from the google analytics file:大约 25% 的时间在加载时,我从谷歌分析文件中得到以下错误:

Uncaught TypeError: a.slice is not a function未捕获的类型错误:a.slice 不是 function

I believe that it is naming interference between objects and functions within two .js files that are on the site, the google analytics js file and I'm not sure what other one.我相信它是在站点上的两个.js文件(谷歌分析 js 文件)中的对象和函数之间的命名干扰,我不确定还有哪个。 When i add a breakpoint in the google analytics file, I can see that when the error occurs, a is referencing an object in another file.当我在谷歌分析文件中添加断点时,我可以看到发生错误时, a正在引用另一个文件中的 object。 It shows up under scope>local in the debugger, and says that it is an object from page.js .它显示在调试器中的 scope>local 下,并说它是来自 page.js 的page.js I've went through that file and made sure that there are no objects or functions named that.我已经浏览了那个文件,并确保没有以它命名的对象或函数。 I believe that it actually coming from leaflet.js which I am using.我相信它实际上来自我正在使用的leaflet.js It seems to be a race condition as to which one loads first gets the name.关于哪个加载首先获得名称似乎是一种竞争条件。 If the analytics file loads first, all's well and everything works correctly, otherwise I get the error.如果分析文件首先加载,一切都很好并且一切正常,否则我会收到错误消息。

It is beyond me to change the leaflet file and I have no control over those two files.我无法更改 leaflet 文件,我无法控制这两个文件。 Is there some way I can prevent conflict between the two files?有什么方法可以防止两个文件之间的冲突吗?

Well... It is not an elegant solution, but you could force leaflet load after analytics loads.嗯......这不是一个优雅的解决方案,但您可以在分析加载后强制加载 leaflet。

Still.仍然。 Stackoverflow uses analytics and I'm not seeing a global a object declared. Stackoverflow 使用分析,我没有看到一个全局a object 声明。 And I've worked with analytics for a while now and never seen it declaring something as ambiguous as a.而且我已经用分析工作了一段时间,从来没有见过它声明像 a 这样模棱两可的东西。 Having something like a in global scope reminds me of minified, unclosured code in global scope.在全局 scope 中有类似a东西让我想起了全局 scope 中的缩小的、未封闭的代码。 Which may be your problem.这可能是你的问题。

This may come from GTM, if leaflet is deployed through it.如果通过它部署 leaflet,这可能来自 GTM。

Anyhow, you didn't do enough debugging.无论如何,你没有做足够的调试。 Try blocking requests to certain JS files to find out exactly which libraries cause the race condition.尝试阻止对某些 JS 文件的请求,以准确找出导致竞争条件的库。 Also make sure GTM is not a case here since it often happens there because people tend to deploy custom html tags of unclosured but minified code.还要确保 GTM 不是这里的情况,因为它经常在那里发生,因为人们倾向于部署未封闭但缩小的代码的自定义 html 标签。 Causes exactly this situation.正是造成这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM