How do I get a global function recognized by my JS file loaded through AJAX? How do I get a global function recognized by my JS file loaded through AJAX? ajax ajax

How do I get a global function recognized by my JS file loaded through AJAX?


Scripts loaded in the main page are not available in web workers, you have to import them with importScripts not the import command

importScripts("base64.js");


In old-fashioned (non-module) javascript files, global variables are implied to be made on window. So in the first example, Base64.decode("abc") is the same as window.Base64.decode("abc"). In modules, however, this is not true. If you want to access a global variable on the window, it must be done explicitly.

In the module, try changing the reference to Base64 to window.Base64.

Sidenote: If the base64.js file works with a basic script tag import, then it will not work to import it as an es6 module like you have done (import {Base64} from 'base64';). You can read up more on how to import modules here!

Hope that helps!

Update

For clarity, here are a couple examples. Basically, what ever you put in the curly braces ({ Base64}) must be exported from the script being imported, not placed on the window.

<script src=".../base64.js"></script><script>  // both are accessible this way because this is NOT a module  // and global variables are assumed to be on the window.  console.log(Base64);  console.log(window.Base64);</script><script type="module">  // Will not work:  // import { Base64 } from ".../base64.js  // import { window.Base64 } from ".../base64.js  // The same as importing view the script tag  // (not needed because the script tag already imported it)  // import ".../base64.js"  // the "global variable" is accessible on the window  console.log(window.Base64)</script>


The issue is with the path you are referring to. Here are valid paths in type module.

// Supported:import {foo} from 'https://jakearchibald.com/utils/bar.js';import {foo} from '/utils/bar.js';import {foo} from './bar.js';import {foo} from '../bar.js';// Not supported:import {foo} from 'bar.js';import {foo} from 'utils/bar.js';

Try referring to the path directly. something like this

import {addTextToBody} from '../../someFolder/someOtherfolder/utils.js';

here are valid pathName

Starts with ./  :- same folderStarts with ../ :- Parent folderStarts with ../../ :- above parentfolder