Where should I declare JavaScript files used in my page? In <head></head> or near </body>?

后端 未结 12 970
后悔当初
后悔当初 2020-11-27 15:07

I was reading a tutorial and the author mentioned to include Javascript files near closing body tag () in HTML.

I was wonderi

12条回答
  •  醉话见心
    2020-11-27 15:48

    The only reason for putting it near the end of the body, AFAIK, is to be able to execute the JavaScript after the web browser has parsed your HTML document. E.g. if your JavaScript deals with "all elements named hello", the browser needs to read the entire document before executing your JavaScript. Makes sense, right?

    In e.g. JQuery, you can put your JavaScript anywhere in your document and use:

    $(document).ready(function () {
      // your code here
    });
    

    ...to make sure the entire document has been loaded into the DOM before executing the inner function. Of course, this can be done with normal JavaScript as well, but be careful not to break compatibility with some browsers, because their needs tend to differ a lot.

提交回复
热议问题