6

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.

4
  • 1
    If one solution works and the other not, it's not about optimization, let alone micro optimization. Just about programming. Commented Aug 29, 2012 at 16:00
  • But "micro-optimization" sounds cooler than "programming." Commented Aug 29, 2012 at 16:01
  • I noticed you don't have an account at code golf, I will assume you haven't seen this post, it's worth looking for JavaScript optimizations Commented Aug 29, 2012 at 16:24
  • What exactly are you trying to optimize? Bandwidth? Lines of code? Client processing time? GET requests? Consider that if you serve jQuery from Google CDN, the client likely has it cached already. Commented Aug 29, 2012 at 16:30

3 Answers 3

9

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.

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

Comments

7

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

2 Comments

This is present in the spec as well, e.g. developers.whatwg.org/scripting-1.html#the-script-element - "If there is a src attribute, the element must be either empty or contain only script documentation that also matches script content restrictions."
I wonder, is `<script type="text/javascript" src="path.js" /> valid? My guess would be no, but why? Edit: ah, found it, only in XHTML in compatible browsers. Still don't get why though..
1

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.

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.