Javascript for different pages.

I've a single file of js with multiple scripts for different pages. Issue is I'm getting one element on a page that is not available on the other page, because of that the script of that page doesn't work. What should be the approach here. Make a different js files for different pages. Or is there another way.
6 Replies
Jochem
Jochem2y ago
that's one option. way back when I'd have one common utility script, then a script per page for each page. Alternatively if the differences are minimal, you can just check to see if the element exists before running the code that's reliant on that element
glutonium
glutonium2y ago
if there's a common script among all pages then wouldn't it work if u make a separate js file only containing that particular script and then adding that to every html?
Jochem
Jochem2y ago
yeah scripts just run in order of inclusion (as long as we're ignoring defer and all that) and share the same global scope, you can split it up however you like
~MARSMAN~
~MARSMAN~2y ago
When i have a common functions between pages but not all share the all the functions, i use import and export. I add all the mutual functions in one file, then use separate files for each page ( if it's a must ) and just import the mutual functions i want to use in that page. Of course along with the page own functions
Jochem
Jochem2y ago
I always forget you can do that in browser now too, last time I used vanilla JS in a new project without a bundler predates that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
~MARSMAN~
~MARSMAN~2y ago
Yep it's a great help for me
Want results from more Discord servers?
Add your server