2

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..

1
  • 1
    What happens when you try it :) Commented Sep 7, 2011 at 20:41

3 Answers 3

2

you can think of it like this:

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

The most recently loaded file wins.

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

2 Comments

for the second case , if the file is duplicated does it even loads it again ? or it can see that he already loaded the file so he ignores...?
It would load it again, probably using a cached copy it just got.
1

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)

Comments

1

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.

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.