如果您使用 <script> 会发生什么?具有相同“src"的标签在单个 HTML 文档中多次使用属性? [英] What happens if you use a <script> tag with the same "src" attribute multiple times within a single HTML document?
问题描述
尽管我几乎可以肯定这个问题的答案将是特定于浏览器的,但是当使用多个 标签并具有相同的 src 属性时,是否有任何浏览器定义了行为?
Although I am almost certain the answer to this question will be browser specific, do any of the browsers define behavior for when multiple <script> tags are used and have the same src attribute?
例如...
<script src="../js/foo.js"></script>
...
<!-- what happens here? -->
<script src="../js/foo.js"></script>
我首先问这个问题的原因是,在我的特殊情况下,我在使用 JQuery 的 ASP.NET MVC 应用程序中使用部分视图.JQuery JS 文件都通过脚本标签包含在主模板文件中.我更愿意将脚本标签添加到部分视图文件,以便万一它们在主模板的上下文之外使用,它们将自动包含所有必要的 JS 文件,而不是依赖另一个视图或模板来包含它们.但是,我当然不希望导致 JS 文件必须多次传输到客户端,或者任何其他可能对用户体验产生负面影响的副作用.
The reason I ask this question in the first place, is that in my particular case I am using partial views in an ASP.NET MVC application which make use of JQuery. The JQuery JS file(s) are all included in the master template file via script tags. I would prefer to add script tags to the partial view files so that in case they are used outside the context of the master template, they will automatically include all the necessary JS files, and not rely on another view or template to include them. However, I certainly don't want to cause JS files to have to be transferred to the client multiple times, or any other side effects that could negatively impact the user experience.
我现在的想法是,大多数(如果不是全部)主要浏览器(FF、Safari、IE、Opera)将在第一次使用时缓存 JS 文件,然后浏览器将在后续的脚本标签上使用缓存副本(如果可用且尚未过期).但是,缓存行为通常可以通过浏览器配置进行更改,因此依赖任何类型的缓存行为似乎都不太安全".
My thinking right now is that most, if not all, of the major browsers (FF, Safari, IE, Opera) will cache a JS file the first time it is used, and then on subsequent script tags the browser will use the cached copy if available and if it hasn't expired. However, caching behavior can usually be altered through browser configuration, so it doesn't seem too "safe" to rely on any kind of caching behavior.
我是否只需要接受这样一个事实,即我的部分视图将依赖于其他模板或视图,包括适当的 JS 文件?
Will I just have to accept the fact that my partial views are going to have be dependent on other templates or views including the appropriate JS files?
推荐答案
即使它们被缓存,您也可能会遇到问题,因为相同的代码将被执行两次.至少,这会导致浏览器花费不必要的时间.它可能会导致错误,因为大多数 JavaScript 代码不是为了执行两次而编写的.例如,它可能会附加相同的事件处理程序两次.
Even if they're cached, you may have problems since the same code will be executed twice. At the very least, this will cause the browser to take more time than necessary. And it may cause errors, since most JavaScript code isn't written to be executed twice. For example, it may attach the same event handlers twice.
这篇关于如果您使用 <script> 会发生什么?具有相同“src"的标签在单个 HTML 文档中多次使用属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!