TheBlackBenzKid
TheBlackBenzKid

Reputation: 27087

Having Script within a Script Src tag? <script> (JavaScript etc)

Why does this not work?

<script type="text/javascript" src="//cdn.com/assets/js/jquery.js">
alert("Hello World!");
</script>

But this does?

<script type="text/javascript" src="//cdn.com/assets/js/jquery.js"></script>
<script type="text/javascript">
alert("Hello World!");
</script>

This is general across many HTML tags that pull from source. Micro optimization is important in my situation and I am also curious.

Upvotes: 6

Views: 2972

Answers (3)

D&#39;Arcy Rittich
D&#39;Arcy Rittich

Reputation: 171381

From w3.org (emphasis mine):

If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

Upvotes: 9

Jakub
Jakub

Reputation: 20475

In the first example you define the src which makes it IGNORE the contents of the <script></script>

In the 2nd example you have 2 separate <script></script> tags, the 2nd of which is housing your code to execute.

Upvotes: 1

DZittersteyn
DZittersteyn

Reputation: 628

from http://javascript.crockford.com/script.html:

"If the src attribute is not present, then the content text between the <script> and the </script> is compiled and executed."

As there is a src attribute, the content is not executed

Upvotes: 7

Related Questions