Sreerup
Sreerup

Reputation: 33

How to access and assign function from a window object in JS?

I have tried to assign a function to a window object like this present in main.js

var _init_ = function(id = "") {
    //do something
}
window._init_ = _init_;

Now I tried calling the function from index.html by attaching a script like this:

<script type="module" src="./main.js"></script>
<script type = "text/javascript">
    _init_();
</script>

But while I refresh the browser it is giving me Uncaught ReferenceError: _init_ is not defined though it is returning the function when I'm trying to access it via window._init_ in the browser console.

Note: I have imported the script as a module as I have broken down the js code into different js files and using it as one

Question/doubt: How to assign and access the function present in window object keeping id as optional, means if id is not passed in function call it will be an empty string or if id is passed it will accept the passed string.

Upvotes: 1

Views: 1702

Answers (2)

Ran Turner
Ran Turner

Reputation: 18026

One approach to achieve this with dynamic loading.

function loadScript() {
  const script = document.createElement('script');
  script.src = "./main.js";
  document.body.appendChild(script);

  return new Promise((res, rej) => {
     script.onload = function() {
      res();
   }
 });
}


loadScript()
 .then(() => {
  console.log('loaded, now you can use what ever you need from main.js');
});

Another one is to use onLoad event:

<script onload="callInit();" type="module" src="./main.js"></script>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370759

Modules run asynchronously. The _init_ is not defined by the time your inline script runs.

While there are ways to get the inline script to take the information from the the module after the module loads, it wouldn't be so elegant. The best approach by far here would be for:

Now I tried calling the function from index.html

to be the entry point itself:

<script type="module">
import { init } from './main.js';
init(); // pass an ID here if you want
</script>
// main.js
export const init = function(id = '') {
  // do something
}

Upvotes: 2

Related Questions