0

Browser loading scripts

<!DOCTYPE html>
<html dir="ltr">
<head>
<script type="text/javascript" src='./value-of-a-is-1.js'></script> <!-- Loads slow as per network tab in chrome -->
<script type="text/javascript" src='./value-of-a-is-2.js'></script> <!-- Loads faster as per network in chrome -->
</head>
<body></body>
</html>

Note: First scripts loads slower than the second script. As I have checked it on network tab for chrome.

Now if Go to console and say console.log(a); what should be the value of variable a (1 or 2)?

Gyandeep
  • 12,726
  • 4
  • 31
  • 42

2 Answers2

3

With the script tags you have, the scripts can be loaded in parallel, but they will run in sequence (one after another), in the order in which they appear in the HTML.

So a will be either undefined (neither script has run) or 2 (both scripts have run), if it's really true that the first script will load slowly, since when it finishes loading, both scripts will run immediately after one another.

To avoid wondering about the timing around you typing in the console, you can do this:

<script>
var a = "initial";
console.log(a);
</script>
<script type="text/javascript" src='./sets-a-to-one.js'></script>
<script>
console.log(a);
</script>
<script type="text/javascript" src='./sets-a-to-two.js'></script>
<script>
console.log(a);
</script>

...where sets-a-to-one.js is a = 'one';, and sets-a-to-two.js is a = 'two';.

You'll reliably see:

initial
one
two

...regardless of the relative load speeds of the scripts.

Note that the async and defer attributes can change this behavior; see the spec for details. (Some browsers may not support them, or may support only one of them, or may have bugs in their support, FWIW.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The correct answer would be 2, the latter script script gets executed last (although it can be loaded parallel).

I.e. the code would look like that when written in just one file:

<!DOCTYPE HTML>
<html>
    <head>
        <script> var a=1; </script>
        <script> var a=2; </script>
    </head>
    <body>
    </body>
</html>
Paul B.
  • 261
  • 1
  • 8