2

Could I encounter any problems if I included a JavaScript or CSS file in one html page more than once? For example:

<html>
<head>
...

<script src="/Scripts/MyScript.js" type="text/javascript"></script>
<script type="text/javascript" src="/Scripts/jquery.js"></script>
<script src="/Scripts/MyScript.js" type="text/javascript"></script>

...</head>
<body>
...
</body></html>

In case anybody wonders why I would want to do something like that: It's more curiosity and I know some projects where it actually occurs. I already checked with Fiddler and the files seem to be requested only once.

2
  • I believe the files are requested only once due to browser cache, but the javascript should be executed each time you put a <script> tag. Commented Aug 4, 2011 at 12:58
  • Yes, I think you are right. I just tried it with an alert box and the code is executed twice (at least in Chrome and IE). Good point - thanks. Commented Aug 4, 2011 at 13:02

2 Answers 2

4

For CSS, it won't have any effect other than to slow down the page rendering by a tiny fraction.

For JavaScript, the code will be executed twice. If the code has side-effects, those effects will apply twice. If all the JavaScript does is (eg.) define some functions, it won't have any appreciable effect.

Under normal circumstances the files will be cached after the first read, so they won't be fetched over the network multiple times.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, It is considered good practice to not put side-effects in .js files anyway, but who knows... :)
1

As RichieHindle says, unless the JS file has side-effects the problems wouldn't be noticeable most of the time.

Where you might get odd behaviour is if you define javascript in between the calls to an external file. Like this:

<script src="lib.js" type="text/javascript"></script>
<script type="text/javascript">
    // Do something with the object created in lib.js
</script>
<script src="lib.js" type="text/javascript"></script>
<script type="text/javascript">
    // Do another thing with the object created in lib.js
</script>

The first block of local code will be using a different version of the object created in lib.js. Any functions or values you assign to it will disappear when lib.js is loaded the second time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.