jenkinz
jenkinz

Reputation: 139

Why is my HTML onload event attribute ignored in the script element?

<!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?

Upvotes: 0

Views: 2980

Answers (4)

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9243

Execute a JavaScript immediately after a page has been loaded:

In HTML:

<body onload="console.log('popup function has been triggered!!!')">

In JavaScript:

window.onload = popup();
function popup()
{
    console.log('popup function has been triggered!!!');
}

In JavaScript, using the addEventListener() method:

window.addEventListener('load', popup)
function popup()
{
    console.log('popup function has been triggered!!!');
}

Upvotes: 1

jenkinz
jenkinz

Reputation: 139

The onload isn't neccessary to kick off the function. I just needed to nonce it:

<script{%- if nonce %} nonce="{{ nonce }}"{% endif -%}>

(That's nunjucks BTW.)

Upvotes: -1

Hubert Hilczer
Hubert Hilczer

Reputation: 95

You have to pass the onload attribute to the body, not the script tag. ==> <body onload=fnc> Also, it would be good practice to add the defer attribute to your scripts tags so that they run after the DOM has loaded

Upvotes: -2

CertainPerformance
CertainPerformance

Reputation: 371138

On an element, the load event fires if the element requires a resource, once that resource has loaded. This applies to, for example, images and <script> tags which use separate files. Inline JavaScript tags do not require the downloading of resources, so they don't fire the load event: so, the

<script onload="popup()">

doesn't invoke popup.

Just run popup() in the plain script body:

<script>
    function popup() {
      console.log('popup function has been triggered!!!');
    }
    popup();
  </script>

If you want to wait for the whole DOM to be loaded, use a DOMContentLoaded listener:

window.addEventListener('DOMContentLoaded', popup);

Upvotes: 4

Related Questions