Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript before onload?

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?

like image 256
NoBugs Avatar asked Aug 21 '11 06:08

NoBugs


People also ask

Can JavaScript run before page load?

You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.

What loads first JavaScript or HTML?

The browser loads the html (DOM) at first. The browser starts to load the external resources from top to bottom, line by line. If a <script> is met, the loading will be blocked and wait until the JS file is loaded and executed and then continue.

What can be used in place of load event in JavaScript?

Solution(By Examveda Team)DOMContentLoaded and readystatechange are alternatives to the load event: they are triggered sooner, when the document and its elements are ready to manipulate, but before external resources are fully loaded.


1 Answers

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.
like image 85
Itay Maman Avatar answered Sep 21 '22 17:09

Itay Maman