Javascript before onload?

If you put Javascript statements (rather than function definitions) inside a <script> tag, they will be executed during page loading – before the onLoad event is fired.

 <html>
 <body>
   <h2>First header</h2>
   <script type="text/javascript">
     alert("Hi, I am here"); 
     document.write("<h3>This is Javascript generated</h3>");
   </script>
   <h2>Second header</h2>
 </body>
 </html>

The caveat is that you cannot search for elements by ID because these element might not have been rendered yet, so your ability to change the page that way is limited.

Bottom line: possible, not recommended.

What I usually do in such situations is as follows:

  • Make the parts of the page that may change invisible (via style="visibility:hidden;");
  • Make onLoad run a Javascript code that changes the page and then sets the visibility of the said parts to visibility:visible.

Leave a Comment