Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
Creating maintainable JavaScript code is important if want to keep using the code.
In this article, we’ll look at the basics of creating maintainable JavaScript code by looking at loose coupling between JavaScript and HTML.
Keep JavaScript Out of HTML
We should keep JavaScript out of our HTML code.
It’s hard to debug JavaScript code that’s in our HTML files.
For instance, if we have:
<button onclick="doSomething()">click me</button>
then we call our doSomething
function when we click on the button.
doSomething
maybe in an external file or in a script tag.
We may run into issues when we click the button before the function is available, which causes a JavaScript error.
The resulting error may pop up and cause the button to appear to do nothing.
It’s also harder to maintain since changing the name would mean we’ve to also look for the name in the HTML file.
We may also want to change the code in the onclick
attribu
Embedding JavaScript code in HTML makes changing the code easier.
Most of our JavaScript code should be in external files and included on the page with a script tag.
The on
attributes shouldn't ve used for attaching event handlers to HTML.
Instead, we should attach the event listeners to the element by getting the element with JavaScript and attaching the listener:
function onClick() {
// ...
}
const btn = document.querySelector("button");
btn.addEventListener("click", onClick, false);
We set the onClick
function as the click handler for the button.
The benefit of that is that onClick
is defined in the same files as the code that attaches the event handler.
If the function needs to change, then we need to change the JavaScript file.
If the button should do something else when it’s clicked, then we just need to change the code in the file.
IE8 and earlier don’t have the addEventListener
method.
Instead, we have to use the attachEvent
method.
With jQuery, we can write:
$("button").on("click", onClick);
We can also embed JavaScript in HTML with a script element that has inline code.
But this isn’t good since it keeps the JavaScript code in the HTML and makes the code longer.
For instance, we shouldn’t write code like:
<script>
doSomething();
</script>
It’s best to keep all JavaScript in external files and keep inline JavaScript out of our HTML.
This helps us debug the code easier.
When a script error occurs, we know the error is in a JavaScript file.
If the JavaScript code is in our HTML file, then we have to search through both kinds of files.
Conclusion
We should keep our JavaScript code out of our HTML code so that we can debug them easier.