How to Call JavaScript Function on Page Load
- JavaScript Function That Takes Variables as Parameter
- JavaScript Call Function That Takes Functions as Argument on Load
A function that can be called whenever the web page is loaded. This convention depends on the browser object window
and its property onload
. The basic way to know that your function is being called is to check the console panel.
For the demonstrative example, we will consider an HTML structure, where we want to visualize how our output will be. And every time we reload the web page, the console panel will respond to a given statement directed by the window.onload
property.
JavaScript Function That Takes Variables as Parameter
Here, we will be using a function that takes variables as arguments. Alongside, the coding drive experimented in jsbin is to grab a better understanding. You can, either way, use your browser and preferable editor.
Code Snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
</head>
<body onload = func()>
<p id="output"></p>
<script>
var x = 40;
var y = 2;
function func(x, y){
return x+y;
}
window.onload = function(){
console.log(func(x,y));
}
document.getElementById('output').innerHTML = func(x,y);
</script>
</body>
</html>
Output:
In this instance, the script portion was added inside the HTML body, and as you can see, on every load of the webpage, the console has a value, which explains that the overall code is functioning.
Additionally, the basic use case for window.onload
is to ensure that the page is successfully loading each time. It is most likely works as a parameter of ensuring an error-free code block in your HTML. So, you can use it anywhere according to your convenience.
JavaScript Call Function That Takes Functions as Argument on Load
The following examples will explain the function of the window.onload
property differently. We will use an HTML code section and an individual JavaScript code section. The parameters of our function are some other functions.
Code Snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
<style>
p{
background: white;
}
</style>
</head>
<body onload = func()>
<p id="output"></p>
</body>
</html>
function f1() {
return '4';
}
function f2() {
return '2';
}
function func(f1, f2) {
return f1() + f2();
}
window.onload =
function() {
console.log(func(f1, f2));
}
document.getElementById('output')
.innerHTML = func(f1, f2);
Output:
From the output scenario, whenever the Run with JS
is pressed, it gives a similar experience of loading a webpage. The code has no error, and that is the inferable statement we can derive from calling a function on each page load.