Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Did I violate some javascript rule?

Tags:

javascript

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 ?

like image 912
tadpole Avatar asked Sep 21 '14 14:09

tadpole


3 Answers

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.

like image 193
dfsq Avatar answered Sep 23 '22 06:09

dfsq


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.

like image 40
Jason Kleban Avatar answered Sep 24 '22 06:09

Jason Kleban


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>
like image 27
antyrat Avatar answered Sep 20 '22 06:09

antyrat