Am I breaking a javascript rule?

I have 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 the string Hello and good bye. I moved the farewell function to my "goodbye.js" file. So my first html now looks like

 <html> <body> <h1>Test function</h1> <p>Hello</p> <script src='goodbye.js'> goodbye(); </script> </body> </html> 

Now, if I run html again, it will only display Hello. I did not expect this. What happened?

+6
source share
5 answers

This is what the W3C specification says:

A script can be defined in the contents of a script element or in an external file. If the src attribute is not set, user agents must interpret the contents of the element as a script. If the src value has a URI value, user agents should ignore the contents of the element and retrieve the script through the URI.

So the correct way to call goodbye() is to add another script tag after the first with the src attribute.

+13
source

I need two script tags. The unit with src must be empty, since its contents are determined by src , and your inline goodbye(); ignored. Make a second tag without src for the goodbye inline call.

+3
source

When the src property is added to the <script> tag, the tag browser will ignore all content below it. Therefore, you need to add an additional <script> :

 <script src='goodbye.js'></script> <script> goodbye(); </script> 
+2
source

You cannot use a script element to load a script and use it as an inline script.

 <html> <body> <h1>Test function</h1> <p>Hello</p> <script src='goodbye.js'></script> <script> goodbye(); </script> </body> </html> 

Alternatively, you can add goodbye (); call the end of goodbye.js.

+2
source

You cannot have the src attribute plus the text content for the script element. If there is an src attribute, it will be used, and text content is ignored.

 <script src='goodbye.js'></script> <script>goodbye();</script> 
+2
source

Source: https://habr.com/ru/post/975604/


All Articles