What's the best way to organize JavaScript code in a web project?

Hey everyone,

I’m trying to figure out the best approach for organizing my JavaScript code in my web projects. I’m wondering if it’s better to:

  1. Write JS directly in each HTML file
  2. Use a single main.js file for all pages
  3. Create separate JS files for different sections

If you use a single file, how do you make sure the code only runs on the right pages? I’m talking about custom JS here, not libraries like jQuery.

I’ve heard different opinions, and I’m curious what experienced devs think. What’s your go-to method? Any tips or best practices you’ve found helpful?

Thanks in advance for your insights!

As someone who’s worked on numerous web projects, I’ve found that a combination of approaches works best for organizing JavaScript code. I typically use a main.js file for global functions and initialization, then create separate files for specific features or pages.

One trick I’ve found incredibly useful is using ES6 modules. This allows you to split your code into smaller, more manageable files while still keeping everything organized. You can then import only what you need on each page.

For ensuring code runs on the right pages, I’ve had success with a simple check in each module:

if (document.querySelector(‘.page-specific-element’)) {
// Run page-specific code
}

This approach has saved me countless headaches, especially when working on larger projects. It keeps the codebase clean, makes debugging easier, and allows for better collaboration with other devs. Just remember to set up your build process to handle module bundling for browser compatibility.

From my experience, creating separate JS files for different sections of your project is the most effective approach. It keeps your code modular and easier to maintain. I typically have a core.js file for shared functionality, then individual files for specific features or pages.

To ensure scripts only run on the right pages, I use a data-attribute on the body tag. For example, . Then in my JS, I check for this attribute before executing page-specific code:

if (document.body.dataset.page === 'home') {
  // Home page specific code
}

This method has worked well for me across various projects, keeping things organized without overcomplicating the structure. It also makes it easier to collaborate with other developers on the same codebase.

yo, i’ve found that using separate JS files for different parts of the site works best. keeps things neat, ya know? i usually have a main.js for shared stuff, then specific files for each feature.

to make sure scripts only run where they should, i use data attributes on the body tag. like . then in the JS, i check for it:

if (document.body.dataset.page === ‘home’) {
// home page code here
}

works like a charm for me!