Tai
Tai

Reputation: 417

why shouldn't we put any javascript code between the <script> tag if we only want to include external js file?

i don't really understand why the author in the "Javascript & Jquery: the missing manual , second edition" advise the sentence below:

When adding the src attribute to link to an external JavaScript file, don’t add any JavaScript code between the opening and closing tags. If you want to link to an external JavaScript file and add custom JavaScript code to a page, use a second set of tags. For example:

what is the advantage of using the second script tag instead of only using one?

Upvotes: 3

Views: 209

Answers (2)

Sparky
Sparky

Reputation: 98738

what is the advantage of using the second script tag instead of only using one?

It's not a matter of "advantage", where both methods work and one is simply better than the other.

It's a matter of "necessity" because if you put code inside the tags used to include an external file, it will not work at all.

No good....

<script type="text/javascript" src="/myfile.js">
   // code in here will be ignored
</script>

Good...

<script type="text/javascript" src="/myfile.js"></script>
<script type="text/javascript" language="JavaScript">
   //  this code will not be ignored
</script>

Upvotes: 2

Quentin
Quentin

Reputation: 944080

Because, when there is a src attribute, the content of the element will be ignored.

From the specification:

The script may be defined within the contents of the SCRIPT element or in an external file. If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

Upvotes: 7

Related Questions