Reputation: 10477
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 come 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.
Upvotes: 5
Views: 3053
Reputation: 113974
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.
Upvotes: 3
Reputation: 154908
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.net/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
}
Upvotes: 3