Reputation: 45806
I'm learning JavaScript along with HTML and CSS. I wrote up JavaScript file, Primes.js, that contains a few prime-finding related functions for testing.
To test out using external .js files, I wrote up the following HTML file:
...
<body>
<script src="Primes.js">
console.log("Loaded...");
var n = 13;
alert(n + " is prime?: " + isPrime(n));
console.log("Ending...");
</script>
</body>
...
But it never executed the statements within the script block.
After looking around, I found this answer, and changed the body to:
...
<body>
<script src="Primes.js"></script>
<script>
console.log("Loaded...");
var n = 13;
alert(n + " is prime?: " + isPrime(n));
console.log("Ending...");
</script>
</body>
...
And magically, it worked as expected. It seems odd requiring an empty script tag to import a file.
Why require that the script tag importing the .js file be empty? Are/were there consequences if scripts were sources in the same tag they were used?
Upvotes: 0
Views: 413
Reputation: 543
As written in w3c the content inside the script is supposed to use for documentation of the script when src
attribute is present.
If a script element's src attribute is specified, then the contents of the script element, if any, must be such that the value of the text IDL attribute, which is derived from the element's contents, matches the documentation production in the following ABNF, the character set for which is Unicode.
Upvotes: 2
Reputation: 3478
The src attribute designates that the script should be imported. The rendering engine will ignore anything placed between the script tags when it sees an src attribute.
Placing text between script tags without the src attribute tells the rendering engine to runs it as inline script.
So do your import, then add your inline scripting between a new set of script tags.
Upvotes: 0
Reputation: 109
Normally, if you were not importing script from another file, you would type the script between the script tags. But since you are importing by declaring a src
, the script in the file you are importing is treated as if it were inserted between the (empty) script tags by your browser.
Upvotes: 0