2

I am fairly new to web development and have been trying to figure out the best way to organize my JavaScript files for the front-end.

The first approach I started with was "one JavaScript file per page", avoiding in-line scripts. Each file would usually attach event listeners and handle any initialization that needed to occur on the page. This was fine until the files started getting huge, and I found myself cordoning off sections for specific page "components" (e.g. a specific table, or a modal).

// SomePage.js

...

//--- User Table Section ---
const user_table = document.getElementById("user_table");
user_table.attachEventListener( ... )

...

//--- Delete Confirmation Section ---
const delete_confirmation = document.getElementById("delete_confirmation");
delete_confirmation.attachEventListener( ... )

...

This prompted me to throw together a "one JavaScript class per component" approach. I define a block of HTML (usually a PartialView) as a component by giving it a data attribute that specifies the JavaScript class that would operate exclusively on it. Each website page loads a single JavaScript file (the "entry point") which searches for this data attribute and uses a mapping of component names to classes to instantiate the appropriate class. The end result is a collection of smaller and more focused script files.

// UserTable.js
export default class UserTable {
    constructor() {
        const user_table = document.getElementById("user_table");
        user_table.attachEventListener( ... )
    }
    // Helper functions go here...
}

// DeleteConfirmation.js
export default class DeleteConfirmation {
    constructor() {
        const delete_confirmation = document.getElementById("delete_confirmation");
        delete_confirmation.attachEventListener( ... )
    }
    // Helper functions go here...
}

// Entrypoint.js
// ...import classes here...
const componentMap = {
    "UserTable": UserTable,
    "DeleteConfirmation": DeleteConfirmation
}
// ...search the page for 'data-component="<component name>"' and call 'new componentMap[<name>]();'

(I don't use a <script> tag in each component's HTML because I believe it would be detrimental to loading times (components are usually PartialViews, so the browser would have to stop processing the HTML and load the script instead), or not work well with bundling since the "defer" attribute requires defining a specific script-- and bundling everything into a single compressed file seems to be standard practice.)

However, this implementation has some problems.

The first is constructing the mapping between the data attribute values and the classes. I can't see any way other than having to manually add a new entry each time I develop a new component. For example, if I create a "UserTable.js" that contains all the JavaScript that operates on the HTML enclosed by a parent with the data-component="UserTable" attribute, I have to go to the entry point file and add "UserTable": UserTable where the value is a reference to the appropriate class. To be honest, this is a relatively small issue, but it makes me wonder if there is a better way of handling things.

The second is that I find myself spending a lot more time trying to figure out the rules I need to follow for this approach to continue working in the future. Things like "should a page allow multiple of the same component?", "should components be allowed to contain other components?", "should I add the ability for components to search for other components on the page, or should every component be fully encapsulated?", etc. These all have their own advantages and disadvantages, which makes it hard to decide when I'm not even sure if my current approach is reasonable or not.

There are some other things I'm not totally certain about, like whether I should be exporting classes or functions (at times, I feel like I'm only using the class for the constructor), or how much I should be caring about caching and minimizing server requests-- but I think my confusion can be cleared up with just a good example of how I'm supposed to be organizing front-end JavaScript files. I'm pretty sure there's a very simple and obvious solution that I'm overlooking, but I can't seem to find it on the Internet.

1 Answer 1

3

All of the approaches you have outlined are valid. I've used many of those myself. The needs of the application have clearly grown. Your description illustrates this gradual increase in complexity very well. Unfortunately, I don't think file organization is the root problem. The root problem, in my opinion, is application architecture.

User interface programming has some challenges that server side programming doesn't. As soon as your users find the application capable of becoming more responsive and modular, the more they expect this. Pretty soon, as you've pointed out, things get nested and complex.

Is time to consider separating concerns even further:

  • Establish a naming convention for classes and files so framework code can infer the file name based on the class name.
  • Loading scripts will be its own part of the framework.
  • Logic to initialize a component from information in the Document Object Model likely needs its own class, and should utilize the script loader.
  • If an explicit mapping of components to classes is desired, then your application needs its own form of a Composition Root. To be honest, even if you don't want an explicit mapping, you likely need a composition root once you reach a certain level of complexity. All this configuration and initialization logic needs to start some place.
  • Yet more logic is required to wire these components together along with their dependencies, making some form of dependency injection necessary.
    • And things get even more difficult with nested components or components that get initialized at runtime rather than page load.

Pretty soon you've invented your own frontend framework, essentially reinventing Angular, React, Vue, or other similar frameworks.

At some point it's worth reassessing if your home grown framework is still capable of supporting an ever-growing application. It might be a good time to make the switch to one of the fully-featured frontend frameworks now before this application becomes too labor intensive to tame. Only you can make that judgement, though. There is no standard practice here. It requires you to understand the bigger picture of this application so you can decide on an architecture that can grow with the feature set.

2
  • Thank you very much for your insight. You've given me some leads to pursue further research on this topic. Sadly, making use of an existing framework is not an option for me, but I will be sure to look into them. I find it especially relieving to know that others have used this DOM-based component design before. I thought I was inventing a hacky workaround to make up for my lack of knowledge, which prevented me from investing too deeply in it. At least now I know where this road will lead. If there are no other replies, I'll be sure to mark this as the answer. Commented Jun 6 at 17:28
  • 1
    @RotundChinchilla, many of the other mainstream frameworks use the same approach -- embed information in the DOM and then some general framework code reads that information to configure and initialize an application. It's a viable approach and a fun project, but a lot of work. Commented Jun 6 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.