Javascript Onload | Onload Event, Document, Window, Image in JavaScript

Javascript Onload


Events related to the onload event:

Example HTML code 1:

This example illustrates the use of the onload event for the body element:

<head>
    <script type="text/javascript">
        function OnLoadDocument () {
            alert ("The document has been loaded.");
            document.body.style.backgroundColor = "red";
        }
    </script>
</head>
<body onload="OnLoadDocument ();">
</body>
Copy Code Print Preview Syntax Highlighter

Did you find this example helpful? yes no

Example HTML code 2:

This example illustrates the use of the onload event for img elements:

<head>
    <script type="text/javascript">
            // Internet Explorer specific
        function OnAbortImage () {
            var info = document.getElementById ("info");
            info.innerHTML += "<br />The loading of the image has been aborted.";
            RemoveEsc ();
        }

        function OnLoadImage () {
            var info = document.getElementById ("info");
            info.innerHTML += "<br />The image has been loaded.";
            RemoveEsc ();
        }

            // Internet Explorer specific
        function OnStateChangeImage (image) {
            var info = document.getElementById ("info");
            info.innerHTML += "<br />readyState: " + image.readyState;
        }

        function RemoveEsc () {
            var esc = document.getElementById ("esc");
            esc.parentNode.removeChild (esc);
        }
    </script>
</head>
<body>
    <span id="info" style="color:red">The image is loading.</span>
    <br /><br />
    <span id="esc">Press the Escape key to abort the process.</span>
    <br /><br />
    <img src="large.bmp" width="200px" height="150px" 
        onabort="OnAbortImage ()" onload="OnLoadImage ()" onreadystatechange="OnStateChangeImage (this)" />
</body>
Copy Code Print Preview Syntax Highlighter

Did you find this example helpful? yes no

Example HTML code 3:

This example illustrates the use of the onload event for XMLDocument objects. Note that this example does not work in Google Chrome and Safari, because they do not support the onload event for XMLDocument objects.

  Code   ajax.js  
<head>
    <script type="text/javascript" src="ajax.js"></script>
    
    <script type="text/javascript">
        var xmlDoc = null;

        function LoadXML () {
            xmlDoc = CreateXMLDocumentObject ();    // defined in ajax.js
            if (!xmlDoc) {
                return;
            }

            var url = "large.xml";
            xmlDoc.async = true;

            if (xmlDoc.addEventListener) {  // Firefox, Opera, Google Chrome and Safari
                xmlDoc.addEventListener("load", OnLoadXML, false);