1

I have a module i18n.js which I import in my home.html, like this:

<html>
  <head></head>

  <body>
    <script type="module" src="../js/lib/i18n.js"></script>
  </body>
</html>

Inside the i18n.js module, I do the following:

export const t = () => {};

//
// Global scope
//

window.t = t;

I understand that accessing the global window object is the way to go in order to be able to call a method from other file inside an HTML page. But... why is this code not working?

<html>
  <head></head>

  <body>
    <p><script>t("title")</script></p>
    <script type="module" src="../js/lib/i18n.js"></script>
  </body>
</html>

I get the error:

Uncaught ReferenceError: t is not defined

1
  • 2
    1. You are loading the script after calling it, hence undefined. 2. Putting code on HTMl will make it readable to everyone. So bad option. Instead, assign a selector to p and set it in JS on load Commented Aug 26, 2022 at 3:52

1 Answer 1

1

Because you're trying to execute t before it's available on the window, you get an error but running the function through the onload as @Rajesh suggested works properly.

const t = () => {
const pTitle = document.getElementById('pTitle');

  if (pTitle){
    pTitle.textContent = 'Hello World!';
  }
};

//
// Global scope
//

window.t = t;

export {
  t
};          
<html>
  <head></head>

  <body onload="t()">
    <p id="pTitle">&nbsp;</p>
  <script type="module" src="./src/js/i18n.js"></script>
  </body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.