Written by Daniel John Dunevant on 2020-02-12 23:23:00
So to get started I want to talk about a concept. That is obtrusive versus unobtrusive Javascript. Obtrusive Javascript means that the javascript is contained within script tags on the html or backend language file (example home.html or home.php respectively). Now this may make it easy to see what’s going on on the page at first because you don’t have to switch to a different document but it really is not worth it and as I’ll show you is just dead wrong.
Unobtrusive Javascript is at first hard to get used to as a programmer starting off. However once you do this it allows for your browser to process your javascript. Meaning when you run your page in the browser you can get a great understanding of exactly what’s going on in your javascript. So now we’ve established that Unobtrusive Javascript is the way to go let’s move on to the next step.
Ensuring your page is ready for your Javascript is a very important step. I’ll tell you what I mean. By ready I mean that the page itself including all its elements (images, scripts, apis, etc) are all loaded. Let’s imagine a worst case scenario.
You don’t make sure your page is loaded before your Javascript is ran. The element that you are referencing in the DOM (Document Object Model) isn’t loaded yet. Your Javascript variable is now null and the script continues with that null variable. An error is seen in your browser’s console and you cry yourself to sleep that night. If only my script would have waited till the page was fully loaded! The humanity!
You don’t want to end up in that situation though. So I’ll show you how to avoid it.
"use strict"; if(window.addEventListener){ window.addEventListener("load", setupPage,false); }else if(window.attachEvent){ window.attach("onload",setupPage); } function setupPage(){ //Other Page setup functions go here createEventListeners(); } function createEventListeners(){ //Event listener code goes here } Starting from the top we have a line with the following: “use strict”; . This makes it so that your console will throw more helpful errors. This is very important in debugging.
Moving on... We have the event listener that will cause your javascript to wait until the page is loaded. The first if checks if a particular event listening function is used in your browser. The same goes for the else if just that it’s checking a different event listening function. For both of these when it’s loaded the script then points to the setupPage function which is where your page element dependent scripting should begin.
On your page there will most likely be more event listeners hence the setupEventListeners function within the setup page.
Now that we’ve covered the framework that we’ll build our validation I’m confident that in the next article we’ll be prepared to start validating some fields as well as other important functions! See ya next time!
