Categories
Javascript Web Development

Why Javascript is not Working in Head Tag?

Why my javascript is not working in Head Tag?

Have you been frustrated, and wonder why the javascript in your <head> tag is not working? Why javascript is not working in head tag?

You must keep in mind that the position of your javascript within the code MATTERS.

Your javascript’s code position with respect to the HTML elements they use, MATTERS.

The javascript code or script (inline or referenced) must be placed below the DOM object (HTML element) it uses or references. Javascript cannot effect the DOM on elements that have not been loaded, so you have to make sure they are loaded first!

Possible Solutions

1. Place the script below the DOM object (HTML element) it uses or references.

ie. The script block must be included at any point after the HTML element tag in the source code of the page.

2. Use window.onload function:

Call the javascript inside the <head> section, but in this case you will need to listen for the window.onload event as follows:

<script>
window.onload = function() {
{{{{{javascript code goes here}}}}}
};
</script>

This function waits until the entire page is loaded before the javascript code is executed.

Javascript not working