How to run a function when the page is loaded?
I want to run a function when the page is loaded, but I don’t want to use it in the <body>
tag.
I have a script that runs if I initialise it in the <body>
, like this:
function codeAddress() {
// code
}
<body onLoad="codeAddress()">
But I want to run it without the <body onload="codeAddress()">
and I have tried a lot of things, e.g. this:
window.onload = codeAddress;
But it is not working.
So how do I run it when the page is loaded?
Solution 1:
window.onload = codeAddress;
should work - here's a demo, and the full code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
</script>
</head>
<body onload="codeAddress();">
</body>
</html>
Solution 2:
Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.
I'd recommend this if you use native Javascript.
document.addEventListener('DOMContentLoaded', function() {
alert("Ready!");
}, false);