开发者

what problems could I encounter if I include a JS or CSS file more than once

开发者 https://www.devze.com 2023-03-26 08:50 出处:网络
Could I encounter any problems if I included a JavaScript or CSS file in one html page more than once? For example:

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&开发者_StackOverflow社区gt;
...
</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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号