Javascript Basics 3 - Dom Ready and Load

Dom Ready and Load events

by Alvaro Silvino

HTML

<div id="op"></div>

CSS

div{margin:15px;}

JavaScript

//do not wrap the JavaScript code, place it in <head> section
//do not wrap the JavaScript code, place it in <body> section
//in this example, we have to do it in no wrap (head) so that domready can use $
//dom ready gets fired when DOM i.e various HTML objects that make up the document are loaded
//load is fired when everything (external images, css, js) are loaded.
this.addEventListener("DOMContentLoaded", domIsReady, true);
this.addEventListener("load", everythingIsloaded, true);

function domIsReady(e) {
    var ct = new Date();
    op = $("#op");
    op.append("DOMContentLoaded (Dom Ready) at " + getCurrentTime() + "<br/>");
}

function everythingIsloaded(e) {
    var ct = new Date();
    op.append("everythingIsloaded (load) at " + getCurrentTime() + "<br/>");
}

function getCurrentTime(){
    var ct = new Date();
    return ct.getHours() + ":" + ct.getMinutes() + ":" + ct.getMilliseconds();
}