Perhaps this is a duplicate question, but I wanted to ask.
I want to make a JS application that does not use third party libraries, for the purpose of learning JS events within a browser.
So I structured my app like this:
var APP = APP || (function (global) { return { digitsField: {}, // other properties, methods init: function (config) { try { this.digitsField = global.getElementById('digitsField'); return this; } catch (error) { console.log(error.message); return false; }; } }; } (window.document));
My html page looks something like this:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/style.css"> <script type="text/javascript" src="js/script.js"></script> </head> <body onload="APP.init({});"> <input type="text" value="0" class="textField" readonly="true" id="digitsField"/> // other html tags </body> </html>
Though I send window.document
to my immediate function, digitsField
tag is still not defined for other workings until the page is loaded or until I call APP.init()
function. I also noticed in Firebug, in the DOM tab that there is is global row dedicated to onload
event which kind of clutters the global namespace. Perhaps there is better way to initialize APP.digitsField
to the tag object without using window.onload
event or third party libraries?
Let me know your thoughts.
Advertisement
Answer
The window onload event fires when everything is loaded, including external resources. You should however only need to wait for the DOM load, so you can attach a handler to the DOMContentLoaded
event:
document.addEventListener("DOMContentLoaded", function() { // code... });
This should be working in browsers newer than IE8 (So IE9 and above).