Search code examples
javascriptajaxfunctionxmlhttprequestglobal

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


I'm confused about scopes in Javascript and how to get a global function recognized. On my page I have

<script src="base64.js"></script>

defined. Then in another file, I have

var xhr = new XMLHttpRequest;
...
        var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
            alert(Base64.decode("abc"));
        xhr.open("get", full + "myotherfile.js", true);
        xhr.send()

The alert executes without a problem. However in the "mytoherfile.js" references to the Base64 class result in a RerefernceError. So at the top of my myotherfile.js I tried

import {Base64} from 'base64';

but this results in a "Uncaught SyntaxError: Unexpected token {" error. What's the right way to include get my global function recognized in a JS file loaded through AJAX?

Edit: The remote loaded JS file is loaded using

this.worker = new Worker(xhrResponseText);

Solution

  • 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");