I have a Javascript code in the string which I want to append to the HTML body. And in that code I want to import some functions from other localization. This is how I am appending Javascript code to the HTML body:
const script = document.createElement('script');
script.setAttribute('type', 'module');
script.text = await view.addScript(); // that function is returning my Javascript code
document.body.appendChild(script);
When I do this I am getting an error: "Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec."
Which I understand. And when I am using appending code other way:
changing:
script.setAttribute('type', 'module');
to
script.setAttribute('type', 'text/javascript');
then I am getting and error: "Cannot use import statement outside a module" which I understand too.
My question is: is it possible to set module Javascript, where code is appended from a string, without setting a src attribute because in my case that src does not exists?
Thanks!
Ok, I solved the problem. When I code this way:
const script = document.createElement('script');
script.setAttribute('type', 'module');
script.text = await view.addScript(); // that function is returning my Javascript code
document.body.appendChild(script);
What was wrong? My script text included import statement. When a path in import is incorrect then you will get a MIME error. When I gave the correct path, the error was gone and now everything is working :)