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!

rocco
  • 115
  • 1
  • 7
  • 2
    So... `import()` your local file just like you were doing with the remote file. Also, note that `import()` is `async`. – Ouroborus Aug 13 '22 at 07:34
  • 1
    isn´t duplicate [here](https://stackoverflow.com/questions/36367532/how-can-i-conditionally-import-an-es6-module) ? – lestra Aug 13 '22 at 07:37
  • 1
    Does this answer your question? [How can I conditionally import an ES6 module?](https://stackoverflow.com/questions/36367532/how-can-i-conditionally-import-an-es6-module) – Ouroborus Aug 13 '22 at 07: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? – rocco Aug 13 '22 at 08:02
  • It doesn't look like [`pwacompat`](https://www.npmjs.com/package/pwacompat) is meant to be loaded via `import`. – Ouroborus Aug 13 '22 at 08:09
  • Then why when I use import() from the CDN it works and when I use it locally it does not? – rocco Aug 13 '22 at 08:12
  • Ok. Thanks to Ouroborus who pushed me to try once more with import() locally, as it appears now it was an absolute path problem with my SSG on build time, which I have now corrected and it works properly now. Thanks also to @lestra: I will definitely use your suggestion, of which I was not aware of, in other contexts. – rocco Aug 13 '22 at 09:06

0 Answers0