21

Is there any event handler before onLoad/onPageShow? The trouble with onLoad is if there is any change in display, the page will show up without change until it is fully loaded, then the script will run. What is the best way to make sure it will run as soon as possible?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
NoBugs
  • 9,310
  • 13
  • 80
  • 146
  • 2
    Synchronous inline script elements will run prior to those events. –  Aug 21 '11 at 06:04

2 Answers2

33

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.
Itay Maman
  • 30,277
  • 10
  • 88
  • 118
  • I think *most* browsers will correctly handle `getElemementById` as long as the element has been previously defined the document -- however, the DOM isn't guaranteed until the onload as pointed out, so it's a slope... :) –  Aug 21 '11 at 06:16
  • 3
    You could also use the DOMContentloaded event which fires when the DOM has completely loaded but not all of the media. OnLoad only fires after all media has been loaded. – citadelgrad Oct 05 '11 at 17:59
-1

The simple answer is to place the function call after the DOM element inside script tags, within the body of your page. I had this problem using a javascript function to style my navigation menu links, however I had a google map element that caused the page to load slowly. On this paticular page, I ran the script just after the link. It is a solution, maybe not the best but it works. Hope this helps.