I am working on a project where I have to inject js code into index.html in a react app. But I have to do this without actually touching the index.html file itself.
I have tried using the script tag in 2 ways:
let script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = src;
document.head.appendChild(script);
In approach 1: I added an external js file instead of the src.
Error: Uncaught SyntaxError: Unexpected token'<'
In approach 2: I used script.innerHTML and added the entire code.
Error: Uncaught SyntaxError: Invalid or unexpected token
Note1: Both errors are coming in the console of the browser
Note2: If I directly add the js code into index.html, everything seems to work
Note3: I have not included the js code because it is of an external library and might deviate the focus from the question, and it might even violate the guidelines for minimum code examples
Neither of the approaches seem to work for me and I have been trying to fix the errors, but I haven't been able to do so. Hence I wanted to ask if there are any other methods to do this as I am unable to find relevant solutions for the same.
Your code works fine in my browser without any errors. Other than adding the script tag, is there any other error? I think there is another error. Take a look at the code again.
// Added script tag to index.html.
// I created an empty file called app.js in the same location as index.html.
const tag = document.createElement('script');
tag.type = "text/javascript";
tag.async = true;
tag.src = './app.js';
document.head.appendChild(tag);