JavaScript - Window Object - The alert() method

In this JavaScript tutorial we will see that the behaviour of the JavaScript alert() method is sometimes not that we can hope.

First of all, let's create a new directory named js and add the myAlert.js script inside:

// js/myAlert.js

Then in our index.html we add this one:

<!DOCTYPE html>
<meta charset="UTF-8">
<title>Alert testing</title>
<script type="text/javascript" src="js/myAlert.js">
<script type="text/javascript">
    function gogogo() {
<body onload="alert('3');gogogo();">
<script type="text/javascript">
Some text.
<script type="text/javascript">

In this example it is expected that the alert() methods are called in this order:

9 - 1 - 2 - 3 - 4 - 5 - 6

Well nay.
Actually, we have as result:

9 - 2 - 5 - 6 - 3 - 4

Weird, isn't it?
The call of the myAlert.js file is in the src property of the <script> tag.
It means that all what is between the <script> and </script> tag are not called because there is already a src property.
So you can add all that you want, it will be never executed.

But after the execution of the two JS functions inside the <body> tag, the functions, in the onload property of the <body> tag, are executed.
So the functions inside the <body> are executed before ones on the onload property of this same <body> tag.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.