简体   繁体   English

如何解决2个冲突的JavaScript文件?

[英]How to resolve 2 conflicting JavaScript files?

如何在不使用JQuery或任何其他外部库或资源的情况下解决2个冲突的,单独的,链接的JavaScript文件?

Based on the conversation we had in the comments, I think I understand what you're asking here and what you mean by "conflicting." 根据我们在评论中的对话,我想我明白你在这里问的是什么,你的意思是“冲突”。

To create a simple example, you have two js files that both use window.onload . 要创建一个简单的示例,您有两个使用window.onload js文件。 The purpose of window.onload is to run the function you assign to it when the window is loaded. window.onload的目的是在加载窗口时运行您为其分配的函数。

Say you have two JS files: 假设您有两个JS文件:

A.js

window.onload = function(){
  console.log("File A")
}

and B.js B.js

window.onload = function(){
  console.log("File B")
}

The problem is that window.onload can only have one function assigned to it a time. 问题是window.onload一次只能分配一个函数。 If you run the following code snippet you'll see that only the string "File B" gets logged to the console. 如果您运行以下代码段,您将看到只有字符串"File B"被记录到控制台。

 <script> window.onload = function(){ console.log("File A") } </script> <script> window.onload = function(){ console.log("File B") } </script> 

Note that the order here IS important. 请注意这里的顺序重要。 Scripts are loaded and executed from top to bottom in your HTML whether they're linked or written inline. 脚本在HTML中从上到下加载并执行,无论它们是内联链接还是内联。 Where it gets confusing is because of Javascript's asynchronous behavior but that's something you'll get an intuition for as you learn. 令人困惑的地方是因为Javascript的异步行为,但是当你学习时,你会得到直觉。

You'll usually want to use addEventListener , on in this case window.addEventListener which will let you add multiple events to the same target (the window being the target in this case, but targets can include almost any element on the page). 你通常想要使用addEventListener ,在本例中是window.addEventListener ,它允许你向同一个目标添加多个事件(在这种情况下,窗口是目标,但目标可以包括页面上的几乎任何元素)。

Note how the below example now logs both strings. 请注意以下示例现在如何记录两个字符串。

 <script> window.addEventListener('load', function(){ console.log("File A") }) </script> <script> window.addEventListener('load', function(){ console.log("File B") }) </script> 

However, you potentially do not need to use the load event at all. 但是,您可能根本不需要使用load事件。 It was historically used as a way to create a scope for modules/libraries/tools so that 3rd party code wouldn't have global variables that conflict just because they use the same name. 它在历史上被用作为模块/库/工具创建范围的一种方式,这样第三方代码就不会因为它们使用相同的名称而产生冲突的全局变量。 This is sort of an advanced topic, so I won't go into detail, but using the window.onload event or the addEventListener variant have for the most part been replaced with using an Immediately Invoked Function Expressions 这是一个高级主题,所以我不会详细介绍,但是使用window.onload事件或addEventListener变量大部分都被替换为使用Immediately Invoked Function Expressions

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

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