Javascript - on Load Function

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

When a Web page is loaded, the code on the page — whether HTML, CSS, PHP, or some other type — is generally processed from the top down. As the browser comes upon a section of code, it's executed and the intended action is (hopefully) performed. Let's say you have the following script in the head section of a Web page:

function func1() {
  alert("This is the first.");
}
 
window.onload=func1;

When the page is loaded, the browser will stop at the script above and execute it. An alert window will pop up and the page will stop loading until the alert window is closed. Often, this isn't an issue, but if the script needs to access elements on the page that aren't yet loaded (i.e., below the current code), you will encounter problems. To resolve these, here are a solution.

3 - On Load Solution

function func1() {
  alert("This is the first.");
}
 
function func2() {
  alert("This is the second.");
}
 
 
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
 
addLoadEvent(func1);
addLoadEvent(func2);
 
addLoadEvent(function() {
    document.body.style.backgroundColor = '#EFDF95';
})

4 - Reference

Advertising
web/javascript/es/onload.txt · Last modified: 2019/03/07 03:42 by 162.158.78.158