开发者

What happens if i have in my document many script with src to the same js file?

just for my knowledge -

what happens if i have 2 equals JS files in my document :

    <script src='A.js'>
and
    <script src='B.js'>

A.js and B.js are equal content .

what happens if i run one func for example which resides in both files ?

which function will fire ? does in memory it has 2 functions开发者_开发技巧 ?

what about this situation :

    <script src='A.js'>
and
    <script src='A.js'>

does it even load it again ?

i need some clarification..


you can think of it like this:

var a = 0;
var a = 1;
alert(a); // 1

The most recently loaded file wins.


case (1): <script src='A.js'> and <script src='B.js'> have the same content:

The file B.js is loaded later, and overrides whatever was defined in A.js. Each function and variable is defined only once, and its value is whatever was assigned to it the last.

case (2): <script src='A.js'> <script src='A.js'> Here, your browser uses caching, for it has no reason to load a file which contents are already known to it. The same is done for images (picture files). Even if you will refresh the page, chances are, the file A.js will not be loaded again, but the cached version will be used (that's if you press F5, Ctrl+F5 will force the browser to reload everything)


The most recent definition of a value or function overrides the previous values. It does not live in memory twice.

However, if the JavaScript files are designed such that by simply evaluating them (when loaded), there is a cumulative side effect, then you could see some very strange behaviors. For example, consider the following:

/* A.js */
document.title = document.title + ", Loaded at" + new DateTime();

/* B.js */
document.title = document.title + ", Loaded at" + new DateTime();

Now, while the contents of these files are identical, you'll actually get a different result for loading both instead of loading just one.

Well designed JavaScript will not result in these types of side-effects after basic evaluation - instead, work done by the JS is typically invoked inside a domReady type function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜