0

I have listen a lot that we should always load the java script at the end of the page why we should do that. If i write the java script at starting of the page how it will make the difference?

  • If you try to use an element in your js code that havent created by DOM yet, what you think will happen? – Batu.Khan May 03 '14 at 11:09
  • 4
    This is a dub. How many times do you think this question has been answered, there are a billion resources on this. Do not tell me google or any other search engine could not find any answers. [Unobtrusive JavaScript: – Ronni Skansing May 03 '14 at 11:11
  • @BatuZet according to my analysis after loading all the elements of dom then it will make that element –  May 03 '14 at 11:15

2 Answers2

2

If you write javascript at the start of the page, than you'll not be able to access the DOM elements, directly.

However when you use it at bottom, all the elements will have been rendered and you can use them.

In the first case, you would need something like this:

window.onload = function(){
  document.getElementById('id');
}

But in the second case, you need just:

document.getElementById('id');

Also, if you have scripts at the start of the page, it will block the UI from rendering.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

If you're using JS to manipulate the DOM, you'll want the page to be loaded before the script is run - usually this means placing the script after the page content.

However, if the Javascript is in response to say an onClick event, you shouldn't need to put it at the base of the page.

Psychemaster
  • 876
  • 10
  • 20
  • 1
    But loading js in the header is a blocking action. So putting it in the bottom is good practice not only when it is about when Dom actions can be performed. – Ronni Skansing May 03 '14 at 11:13
  • You make a good point, sir. I never mentioned putting it in the header specifically, but you're right nonetheless. – Psychemaster May 03 '14 at 11:18