Skip to content

Instantly share code, notes, and snippets.

@tomaslibal
Last active December 30, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomaslibal/7881076 to your computer and use it in GitHub Desktop.
Save tomaslibal/7881076 to your computer and use it in GitHub Desktop.
Simple timing of the loading events on a HTML document using JavaScript.
/**
* As the simple HTML document is loading, the script measures the time it
* takes to reach the given 'readyStates' of the DOM and of the whole
* document.
*
* document.readyState documentation:
* - http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#current-document-readiness
* - https://developer.mozilla.org/en-US/docs/Web/API/document.readyState
*
* window events documentation:
* - http://www.w3.org/TR/DOM-Level-3-Events/#event-type-load
*
* @version December 2013
*
* Example output:
*
* Changing the state to: interactive
* stateInteractive: 7.311ms
* stateDOMLoaded: 7.377ms
* Changing the state to: complete
* stateComplete: 96.937ms
* stateWindowLoad: 97.153ms
*
* Note that starting the timer is a blocking operation so the timers in
* this example aren't started at the same moment but rather one after
* each other which in turn lowers the precision of the measures.
*/
// JS Hint:
/*globals console: true */
// JS Lint
/*jslint browser: true */
console.time("stateLoading");
console.time("stateInteractive");
console.time("stateDOMContentLoaded");
console.time("stateComplete");
console.time("stateWindowLoad");
document.onreadystatechange = function () {
"use strict";
console.log("Changing the state to: ", document.readyState);
// According to the specification, the readyState == 'loading' should be
// assigned on the document creation. That is before this script can
// register that state because the script hasn't been loaded.
if (document.readyState == "loading") {
console.timeEnd("stateLoading");
}
// This seems to be an alternative to DOMContentLoaded.
if (document.readyState == "interactive") {
console.timeEnd("stateInteractive");
}
// This seems to be an alternative to window.onload event.
if (document.readyState == "complete") {
console.timeEnd("stateComplete");
}
};
document.addEventListener("DOMContentLoaded", function() {
"use strict";
console.timeEnd("stateDOMLoaded");
});
window.onload = function () {
"use strict";
console.timeEnd("stateWindowLoad");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment