2

I am importing in my main JS another JS from a CDN conditionally like this:

if (('standalone' in navigator) && (!navigator.standalone)) {
  import('https://unpkg.com/pwacompat');
}

But I'd like to self-host it and include this JS file into my main JS file with JavaScript in the browser method. Like this:

pwacompact.js:

function pwacompact() {
     console.log("pwacompact");
}
export { logpwacompact };
// here goes the js I want to import...

main.js:

// ... other functions preceding the conditional import statement, and then:
if (('standalone' in navigator) && (!navigator.standalone)) {
  import { pwacompact } from "pwacompact.min.js";
logpwacompact();
}

The problem in main.js is that I want to place this import at the bottom of the script, but I can't because I get a Parse error: The import statement may only appear at the top level.

Please, how can I solve this? How can I include the second JS into the main JS and load it conditionally?

Thanks!

7
  • 2
    So... import() your local file just like you were doing with the remote file. Also, note that import() is async. Commented Aug 13, 2022 at 7:34
  • 1
    isn´t duplicate here ? Commented Aug 13, 2022 at 7:37
  • 1
    Does this answer your question? How can I conditionally import an ES6 module? Commented Aug 13, 2022 at 7:37
  • @Ouroborus I was trying that before, but for some reason the script does not work when I self host it and import() locally. I don't know why. I'm still investigating. It could be because I have the main JS defered and, as you say, the import() is async? Commented Aug 13, 2022 at 8:02
  • It doesn't look like pwacompat is meant to be loaded via import. Commented Aug 13, 2022 at 8:09

0

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.