有没有办法阻止脚本加载两次?JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20094139/
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-27 17:41:09  来源:igfitidea点击:

Is there a way to stop scripts from loading twice? JavaScript

javascript

提问by Daft

I have an application with multiple pages which loads dozens of external scripts.

我有一个包含多个页面的应用程序,它加载了数十个外部脚本。

Some pages includeother pages, which means several scripts are loaded multiple times.

一些页面包含其他页面,这意味着多个脚本被多次加载。

Is there any way I cold check which scripts are being loaded and then stop them from being loaded a second time? And improve performance.

有什么办法可以冷检查正在加载哪些脚本,然后阻止它们再次加载?并提高性能。

Sorry I have no code examples, I am just beginning to tackle this issue.

抱歉,我没有代码示例,我才刚刚开始解决这个问题。

Would anyone have any suggestions?

有人会有什么建议吗?

回答by vogomatix

Yes, your scripts can create objects and you can prevent reload if the object exists already

是的,您的脚本可以创建对象,如果对象已经存在,您可以防止重新加载

See Can i use javascript to prevent Loading the same script over and over?for more information

请参阅我可以使用 javascript 来防止一遍又一遍地加载相同的脚本吗?想要查询更多的信息

Another way round the problem is to use a module loader such as require.jsto manage loading your Javascript files. You will have to convert your Javascript files into "modules" which are compatible with require, but the module format is widely used. As this is a standard and not a home-brewed approach it is possibly a better idea than my previous suggestion.

解决该问题的另一种方法是使用模块加载器(例如require.js)来管理加载 Javascript 文件。您必须将 Javascript 文件转换为与 require 兼容的“模块”,但模块格式被广泛使用。由于这是标准而不是自制方法,因此它可能比我之前的建议更好。

回答by Pat Dobson

I'd place a console.log("scriptname - loaded") in each distinct file. Then, using console you can see which scripts are loaded multiple times.

我会在每个不同的文件中放置一个 console.log("scriptname - loaded") 。然后,使用控制台您可以查看哪些脚本被多次加载。

If you includea page, it really shouldn't have all the generic scripts and headers in anyway...

如果你包含一个页面,它真的不应该包含所有的通用脚本和标题......

回答by Fenton

Your browser will do this for you - if the scripts are being loaded from the same URL - as the browser will cache the JavaScript files and load them form the cache rather than requesting them over HTTP.

您的浏览器将为您执行此操作 - 如果脚本是从相同的 URL 加载的 - 因为浏览器将缓存 JavaScript 文件并从缓存中加载它们,而不是通过 HTTP 请求它们。

If different pages load the same script (for example jQuery) but from different URLs, both will be requested as the cache is per-address.

如果不同的页面从不同的 URL 加载相同的脚本(例如 jQuery),则两者都将被请求,因为缓存是按地址进行的。