0

I have a simple question, and there is an answer but I want to know which is better.

When loading scripts through the <script> tag is it better to assign the script in header or body?

A book I am reading, "html5 game development by example", says to put the scripts right before the ending </body> tag, so that the entire page loads first (because, if a script does not load it will render the page useless).

Where as, if I use, an onLoad argument with an additional loading check for jQuery load (jQuery website says not to use onLoad with jQuery, so this is my work around), it should all be readily available? Without, the page getting stuck?

Is there a better, standardised method, that will keep my sanity in check?

    <body onload="init()">

    <!-- HTML code here -->

    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>

    function init() { 
      $( document ).ready(function() {
        jQueryReady();
      });
    };

    function jQueryReady(){

      // $( "p" ).text( "The DOM is now loaded and can be manipulated." );

      // call remaining functions...

   };

   </script>
Liam
  • 27,717
  • 28
  • 128
  • 190
  • possible duplicate of [Should I write script in the body or the head of the html?](http://stackoverflow.com/questions/3531314/should-i-write-script-in-the-body-or-the-head-of-the-html) – Jud Nov 15 '13 at 01:22
  • Possible duplicate of http://stackoverflow.com/questions/196702/where-to-place-javascript-in-a-html-file – slider Nov 15 '13 at 01:22
  • Putting scripts at the end of the body is an extremely robust alternative to all the other methods of running scripts as soon as the DOM is ready. It has all the benefits of a "ready" or "load" listener and also works in any browser that supports scripting. – RobG Nov 15 '13 at 01:42

1 Answers1

2

You do not need init when you use document.ready, as document.ready will ensure to execute the script only when DOM is ready.

$(document).ready(function() {
    jQueryReady();
});

JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts, Reference.

Adil
  • 146,340
  • 25
  • 209
  • 204