Let’s take a look at the classic class name example.
Alright, let’s look at the initialisation logic.
Let’s give this a shot using data attributes and examine the differences.
We fetch all nodes matching having a
data-module attribute. While looping over those nodes we get the name of the module from the
data-module attribute itself and then reference it on the global scope (
window[name]). Done. Single loop.
While our classic
getElementsByClassName method performs a little bit better than the
querySelectorAll method the later unlocks advantages that outweigh this performance difference.
data-moduleattribute, that’s it.
- Because the modules are loaded in a single loop the order in which the modules load is out of your control. Meaning you’ll have to improve your code to better test if everything is ready for a module to load.
- Once you’ve got this setup, you never have to touch it again, with the classic class name version you have to keep adding loops for each new functionality.
- You can easily take this to the next level by defining modules using UMD. This way you can load your module async using a module loader with the advantage that you’ll no longer have to embed the
<script>tag manually. Total separation.
The above is a stepping stone. Because of a better separation of concerns you’ll force yourself to think more modular. This results in cleaner, more reusable and maintainable code.
Give data attributes a go, you’ll never look back!