1

Given an external javascript file with autoexec function syntax:

// external-script.js
(function() {
  console.log('external script called');
}());

With the following <script> tag, the external script doesn't execute:

<body>
  // ...
  <script src="external-script.js" type="text/javascript" />
</body>

But if I add an empty <script> block, as shown below, then the external script executes automatically.

<body>
  // ...
  <script src="external-script.js" type="text/javascript" />
  <script>
    // empty
  </script>
</body>

Why does the addition of the empty <script> block trigger the autoexecute?

CtrlDot
  • 3,102
  • 3
  • 25
  • 32

1 Answers1

3

"self-closing" script tags using /> are not valid HTML syntax. Instead, you must always use <script></script>.

<script src="external-script.js" type="text/javascript"></script>

What is happening in your second example is that you are creating a single script tag with <script>//empty as its contents but this gets ignored since it will run the code from the src attribute.

In fact, HTML parsers just ignore all the / inside open-tags. Instead, some tags are always considered to be void elements with no contents (so <img> doesnt need a matching </img>.

For more info see Are (non-void) self-closing tags valid in HTML5?. Keep in mind that HTML5 is basically just a standard that documented the zany behavior that HTML parsers had already been doing all along.

Community
  • 1
  • 1
hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Shouldn't then the script evaluate when the end of the document is reached, due to tendency of browser to "fix" the html? According to result the script is ignored altogether, but by any chance do you know why? – eithed Jul 26 '14 at 20:54
  • @eithedog: I honestly dont remember. That said, if you use your browser's development tools you should be able to see the tree structure of your document after it was parsed. This should let you see what was considered to be inside the script tag. – hugomg Jul 26 '14 at 20:56
  • For a simple document ``. What is interesting that script doesn't run and the console doesn't display any JS errors (Syntax Error should be in place). I guess that JS preprocessor won't work at all because indeed no end of script was encountered and the "fixing" happens afterwards. Quirky :D – eithed Jul 26 '14 at 21:01
  • @hugomg - the browser (Chrome) inserted closing

    ,

    – CtrlDot Jul 26 '14 at 21:02
  • 1
    @NickHebb: I think you got the order wrong. The first body and html tags are the ones you wrote and they will be considered as Javascript code instead of as HTML tags. then the document ended so the browser closed the script, body and html elements in that order. – hugomg Jul 26 '14 at 21:04