两次包含相同的JavaScript库有什么危险? [英] What is the danger in including the same JavaScript library twice?

查看:113
本文介绍了两次包含相同的JavaScript库有什么危险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的其中一个webapp由许多部分HTML文件组成。如果partial需要一个JavaScript库,例如YUI,则YUI库包含在partial中。

One of the webapps I'm working in is made up of many partial HTML files. If the partial requires a JavaScript library such as YUI, the YUI library is included in the partial.

当部分在运行时合并时,生成的HTML通常会多次包含YUI库。

When the partials are combined at runtime, the resulting HTML often includes the YUI library several times.

<html>
... 
<script type="text/javascript" src="/js/yahoo/yahoo-min.js"></script>
... 
<script type="text/javascript" src="/js/yahoo/yahoo-min.js"></script>
... 
<script type="text/javascript" src="/js/yahoo/yahoo-min.js"></script>
...
</html>

我看过多次包含jQuery的奇怪行为,特别是在使用AJAX时。具体来说,为什么不止一次将同一个JavaScript库包含在一个坏主意中呢?为什么它有时只会导致问题?

I've seen strange behavior from including jQuery several times, especially when using AJAX. Why, specifically, is including the same JavaScript library more than once a bad idea? Why does it only sometimes cause problems?

推荐答案

根据库的不同,包括它可能会产生不良影响。

Depending on the library, including it more than once could have undesired effects.

想象一下,如果你有一个脚本将点击事件绑定到一个按钮,并且你包含该脚本两次,当按钮是这样时,这些动作将运行两次单击。

Think of it like this, if you have a script that binds a click event to a button, and you include that script twice, those actions will be ran twice when the button is clicked.

您可以编写一个简单的函数,您可以调用该函数来加载脚本并让它跟踪已经加载的文件。或者,我确信您可以使用预先存在的JS加载程序(如LabJS)并对其进行修改。

You could write a simple function that you call to load a script and have it keep track of files that have already been loaded. Or, I'm sure you could probably use a pre-existing JS loader such as LabJS and modify it.

这篇关于两次包含相同的JavaScript库有什么危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆