Click here to Skip to main content
15,398,432 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a Javascript module called out.js
JavaScript
export default function out(str) {
  //Some Code
  console.log(str);
}

I ran the webpack bundler and created a bundle.js file.
And now I am Importing it to my index.html using a <script> tag.
JavaScript
<!DOCTYPE html>
<html>
  <head><script defer src="bundle.js"></script></head>
  <body>
    <script>
      out("Hello")
    </script>
  </body>
</html>

I get this error.
index.html:6 Uncaught ReferenceError: out is not defined


What I have tried:

I have tried named exports as well as default exports for the out.js, still I get the same error.
Posted
Updated 24-Jun-21 22:23pm

1 solution

It's likely you could be getting this error because your body > script tags are being processed before the entire document has had the chance to load it's required resources, especially since you've added the defer attribute (which tells a script not to execute until the page has been completely parsed).

You need to add proper document state processing to ensure that any JS built into the page isn't run until the document is ready:
JavaScript
function onLoaded(fn) {
  if (document.readyState == 'complete' || document.readyState == 'interactive')
    setTimeout(fn, 1);
  else
    document.addEventListener('DOMContentLoaded', fn);
}

onLoaded(function () {
  out('Hello');
});

Alternatively you could consider putting the JS in another JS file and include it in the page after the bundle.js file. Also, fair credit to this StackOverflow answer[^] for the basis of this answer.
   
Comments
Manan Sharma 2021 25-Jun-21 12:18pm
   
Hey, thanks for the answer. I don't need the function to be called as soon as the page loads, instead, I want it to be fired on any particular event. Can you help with that?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900