Reputation: 151115
If I have multiple <script>
tags pointing to the same Javascript resource, does the browser run once for each <script>
tag? Or does the browser de-duplicate?
What happens in this case?
<script src="example.js"></script>
<script src="example.js"></script>
Upvotes: 2
Views: 1221
Reputation: 151115
example.js
gets run for every time that it is referred to by a script tag. The browser does not attempt to de-duplicate it. (It may however request it only once from the server.)
This is true even with async
and defer
attributes.
If for some reason, you wanted to support duplicate script tags that cause code only to run once, you could a technique similar to include guards for C.
For instance, example.js
could contain:
if (window.example === undefined) {
window.example = {
publicFunction: function publicFunction() {
// ...
},
// ...
};
}
Upvotes: 2