I have a very simple html and javascript.
<html>
<body>
<h1>Test function</h1>
<p>Hello</p>
<script>
function goodbye() {
document.write ("good bye");
}
goodbye();
</script>
</body>
</html>
The result displays a Hello and good bye string. I moved the goodbye function to its own file "goodbye.js" So my first html now looks like this
<html>
<body>
<h1>Test function</h1>
<p>Hello</p>
<script src='goodbye.js'>
goodbye();
</script>
</body>
</html>
Now if I run the html again, it only displays Hello. I did not expect that. What happened ?
This is what W3C specification says:
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.
So the correct way to call goodbye()
is to add one more script
tag after the first one with src
attribute.
You need two script tags, I believe. The one with src
should be empty, as its contents are defined by src
and your inline goodbye();
is ignored. Make a second tag without a src
for the embedded call to goodbye
.
When you add src
property to <script>
tag browser will ignore all contents under it. So you need to add additional <script>
tag:
<script src='goodbye.js'></script>
<script>
goodbye();
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With