-1

a)

<!doctype html>
   <html>
        <head>
            <title>An example for object method</title>
            <script src= "js/test.js"></script>
        </head>
        <body>
            <h3>Here is an example for object method</h3>
            <p id = "demo"></p>
         
       </body>
</html>

b)

<!doctype html>
 <html>
     <head>
         <title>An example for object method</title>
        
     </head>
     <body>
         <h3>Here is an example for object method</h3>
         <p id = "demo"></p>
         <script src= "js/test.js"></script>
     </body>
</html>

How will these two blocks of code differ while loading a webpage? The first block is not loading the JavaScript file, while the second one is running fine.

Pang
  • 9,564
  • 146
  • 81
  • 122
  • 1
    possible duplicate of [Where to place Javascript in a HTML file?](http://stackoverflow.com/questions/196702/where-to-place-javascript-in-a-html-file) – Samurai May 17 '15 at 05:22

1 Answers1

1

In the second snippet, the js/test.js code does not run until AFTER the HTML has been loaded. This allows it to directly access anything in the DOM. For example if that script does var obj = document.getElementById("demo");, it will return the demo DOM object.

In the first snippet, the HTML of the page is not yet available when js/test.js runs. If the script does var obj = document.getElementById("demo");, it will return null because that DOM object is not yet available (has not yet been loaded).

See this answer (pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it) for a more in depth discussion of this topic and an option for how to make code in the first option "wait" to execute until the DOM is ready.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979