I’m trying to add content to a <div> using AJAX. I also need to load a JavaScript file in the footer after the AJAX call. My menu uses URL hashes to load content without refreshing the page.
The problem is that when I click the same link multiple times, the JS file gets loaded repeatedly. This causes events to fire multiple times. I want to check if the file is already in the DOM before loading it.
I’ve dealt with this exact issue in a couple of projects. One approach that worked well for me was using a data attribute to mark loaded scripts. Here’s how you could modify your ScriptLoader:
This method adds a data-src attribute to each loaded script, which you can then check before loading. It’s straightforward and doesn’t require maintaining a separate list of loaded scripts. Plus, it’s resilient to page refreshes since it checks the actual DOM.
I encountered a similar challenge in a project recently. One effective approach is to maintain a Set of loaded script URLs. Before adding a new script, check if it’s already in the Set. If not, add it to both the DOM and the Set. Here’s a modified version of your ScriptLoader:
This method ensures each script is loaded only once, regardless of how many times it’s requested. It’s efficient and doesn’t require querying the DOM each time.