External JavaScript Not Running, does not write to document

前端 未结 4 1403
我寻月下人不归
我寻月下人不归 2021-01-13 17:14

I\'m trying to use an external JavaScript file in order to write \"Hello World\" into a HTML page.

However for some reason it does not work, I tried the same functio

相关标签:
4条回答
  • 2021-01-13 17:28

    You're trying to call the function before it has been loaded.

    Place the load script above the declaration:

    <html>
    
        <head>
    <script type="txt/javascript" src="hello.js"></script>
        </head>
    
    <body>
    
        <p id="external">
    
            <script type="text/javascript">
                externalFunction();
            </script>
        </p>
    
    
    
    </body>
    
    </html>
    

    Also you have a typo:

     <script type="txt/javascript" src="hello.js"></script>
    

    Should be:

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

    The script type needs to be "text/javascript" not "txt/javascript".

    0 讨论(0)
  • 2021-01-13 17:37

    Script tags with SRC values do not run the contents. Split it to two script tags. One for the include, one for the function call. And make sure the include is before the call.

    0 讨论(0)
  • 2021-01-13 17:48

    use onload eventListener to make it simple

    <script>
       window.onload = function() {
          externalFunction();
       }
    </script>
    
    0 讨论(0)
  • 2021-01-13 17:49

    In general, you want to place your JavaScript at the bottom of the page because it will normally reduce the display time of your page. You can find libraries imported in the header sometimes, but either way you need to declare your functions before you use them.

    http://www.w3schools.com/js/js_whereto.asp

    index.html

    <!DOCTYPE html>
    <html>
    
    <head>
      <!-- You could put this here and it would still work -->
      <!-- But it is good practice to put it at the bottom -->
      <!--<script src="hello.js"></script>-->
    </head>
    
    <body>
    
      <p id="external">Hi</p>
    
      <!-- This first -->
      <script src="hello.js"></script>
    
      <!-- Then you can call it -->
      <script type="text/javascript">
        externalFunction();
      </script>
    
    </body>
    
    </html>
    

    hello.js

    function externalFunction() {
      document.getElementById("external").innerHTML = "Hello World!!!";
    }
    

    Plunker here.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题