javascript - In HTML, if you load the same script file a second time, will it still be loaded? - Stack Overflow

admin2025-04-18  0

Say you have the following in an HTML file:

<script type="text/javascript" src="whatever.js"></script>
<script type="text/javascript" src="whatever.js"></script>

Will whatever.js be loaded a second time, or will the browser see that it's already been loaded and skip re-loading it?

NOTE: This has e up for me because I'm using HTML templates which include other code snippets, some of which may load the same scripts, leading to possible duplication. I want to make sure my pages aren't weighed down by duplicate script loads.

Say you have the following in an HTML file:

<script type="text/javascript" src="whatever.js"></script>
<script type="text/javascript" src="whatever.js"></script>

Will whatever.js be loaded a second time, or will the browser see that it's already been loaded and skip re-loading it?

NOTE: This has e up for me because I'm using HTML templates which include other code snippets, some of which may load the same scripts, leading to possible duplication. I want to make sure my pages aren't weighed down by duplicate script loads.

Share asked Sep 3, 2012 at 17:43 Ghopper21Ghopper21 10.5k12 gold badges65 silver badges92 bronze badges 2
  • AFAIK it will be loaded twice. Load the page in firebug and look in the NET tab (or look in Chrome) – mplungjan Commented Sep 3, 2012 at 17:47
  • I'm guessing cache control will have an impact; is the situation you're specifically asking about is whether the parser is cache aware of identical file requests? Also, this fiddle seems to suggest with that file I've included it's actually downloading only initially (due to caching): jsfiddle/L55j3 – Jared Farrish Commented Sep 3, 2012 at 17:50
Add a ment  | 

2 Answers 2

Reset to default 3

It depends on what you mean by "skipping" the loading.

If you want to avoid hitting the server twice then setting up proper cache controls on the server will avoid the file from being downloaded twice.

If you want to avoid the file from being executed twice then the answer is no: the browser will not skip executing the file the second time. You can get around this by wrapping the file in a giant 'if' statement and check for a global variable or HTML element to test if the file have been loaded before.

Yes, it will reload it. What you can do is checking whether the current script element is already apparent in a "loaded" list that you keep track of: http://jsfiddle/kvPcU/1/.

Somewhere on the top of your page, before you fetch the files:

var loaded = {};

Then:

var elements = document.getElementsByTagName('script');
var currentElement = elements[elements.length - 1];  // element of currently executing script
if(!loaded[currentElement.src]) {
  loaded[currentElement.src] = true;
  // run code
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744931370a275176.html

最新回复(0)