javascriptecmascript-6moduledomcontentloaded

DOMContentLoaded is being called twice when using a module


I am including a module on my page with the following tag:

<script src = "js/manage.js" type = "module"></script>

In that module I am adding an event listener for DOMContentLoaded with the following code:

window.addEventListener('DOMContentLoaded', function() {
  console.log('DOM Content Loaded');
  init();
}, {"once":true});

The problem is that the DOMContentLoaded event is firing twice and my init function is being called twice. I added a console.log() to the init function so I can see when it is called/where it's being called from, too. This is what I see in Chrome's JS console:

Screenshot of Chrome JS console showing duplicate function calls

You can see that both are called twice, but in one instances the location is "manage.js" and in the other it's "manage".

I don't think that the issue is with the code that I've shown here, because I've used this same approach for other projects and I've never had this problem. I've tried searching with Google and on SO (that's where I got the idea to add the "once" directive) but so far I can't find any possible reasons for this to be happening.

I also tried replacing the anonymous function in the event listener with just adding init directly, like this:

window.addEventListener('DOMContentLoaded', init, {"once":true});

But the result was the same (minus the lack of the log entry for the DOMContentLoaded event).

At this point, I am really just looking for some direction for my troubleshooting - I'm at a loss for what to check or where to look next so if anyone has any ideas for what could possibly cause something like this (and also if someone can explain the difference between "manage" and "manage.js" that I'm seeing in the console since I have a hunch that that is related.) I would appreciate it. Thanks!


Solution

  • I was able to solve this with help from comments from @barmar.

    The problem was that, in another module, I was importing two functions from manage.js, but I was not specifying the file extension (.js). Because I had specified the extension when including the module in the <script> tag, the browser was seeing them as two separate files and so was including it twice. By adding the file extension to my include directive, it prevented the event listener from being added twice.