I am building a multi-page web-app in HTML/CSS/JS/jQuery + Vite.js. This is a question about best practices.
There are over 24 pages in the app, so it’s a fairly large codebase. I have been building the whole thing myself (for a small startup) and attempting to follow best practices so that it’s not a nightmare for another developer to take over someday. One issue I keep running into is how to deal with basic functions that every page uses, such as checkLogin
(runs on page load) or hideSections(arr)
(pass in array of dom elements to hide). In those scenarios, is it better to define the functions over and over on each page, or to define it globally in a main script that all pages can access? While I’m aware that globals are bad, I’m struggling with how to avoid potentially having to make changes to one function over and over on each individual page script.
How can I be mindful of scoping, maintainability, readability, and all the other issues associated with global variables, while also avoiding rewriting the same function and having to make edits on every individual page script?
4
Answers
Write the function in a module.
Import it from the module in each other module you want to use it.
There is a difference between global "variables" and "globally accessible functions". Globally accessible functions (functions accessed via .js library files) are certainly not bad. Global variables are.
If you need function reuse, absolutely put it into a .js library file and reference that file from all pages that need the function. And, when you write the functions in that .js file, use the module pattern or define your own namespace to access the function(s).
Module Pattern:
Custom Namespace:
the best solution for this in my perspective is using import/export, for example: utils.js will contain all your utilities functions and you can import specific functions from it, here is a small code snippet
HTML:
utils.js:
or you can make a folder for functions, name each file as function name and export it, now you can import each function by name
One solutions would be to use some Context API such as the react context api or Redux. You could wrap it all with the context provider.
example:
The context would run the function every time it renders, and you could use useMemo() avoiding innecesary renders for better performance.