<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Test!!!</h1>
<script onload="popup()">
function popup() {
console.log('popup function has been triggered!!!');
}
</script>
</body>
</html>
When the above page loads, I expect the onload attribute to cause function popup to fire but nothing happens. Where am I going wrong?
onload="popup()"event to body attributeonloadon a script tag works only when you're loading a resource. Since you are defining the function inline, it will not work here. You can either make it a self-initiating function or simply call it after the function definition.onloadhas its uses, but given your simple example it's probably the wrong thing to be considering. You may be looking at an old old old tutorial? It's usually better to use the DOMContentLoaded event as seen in this SO answer or load a script with defer.