I can't for the life of me figure out why this external JS file isn't loading. I've tried every help question out there and it still won't work so maybe someone else can see what I can't.
So I'm working on a ReactJS project and I'm trying to link an external JS file.
The external javascript file is in public/js/script.js.
I've tried every method I've found to get it to work.
I've linked it in index.html as follows:
<script src="./js/script.js" type="text/jsx"></script>
I've added the following to my main App component:
componentDidMount() {
const script = document.createElement('script');
let url = '../public/js/script.js'
script.src = url; //(This is external js url)
script.async = true;
document.body.appendChild(script);
}
I've added this into the functional component where I really need the external javascript to work:
useEffect(() => {
const script = document.createElement('script');
script.src = '../public/js/script.js'; //(This is external js url)
script.async = true;
document.body.appendChild(script);
}, [])
And yet not matter any of these attempts nothing seems to make the file work.
I am running the project on localhost, so I'm not sure if there's an issue there. I'd just like to figure out how to make external javascript files work. I've tried using Helmet.
I don't know what I'm doing wrong. Anyways, appreciate any help I can get trying to figure this out.
Edit:
I did adjust the following:
src="./js/script.js
to
src="js/script.js in the <script> tag
and it also has had no effect. Still looking for a solution.
Original Code:
<script src="./js/script.js" type="text/jsx"></script>
Changed code: (changed to relative directory)
<script src="js/script.js" type="text/jsx"></script>
Put /js/script.js inside public folder, then add this line beetwen head tag. (no dot prefix)
If you put under body tag, this line will be overwritten when React start to render elements.
<script src="/js/script.js" type="text/jsx"></script>
Or, another way; try to change this line:
let url = '../public/js/script.js'
to:
let url = `${process.env.PUBLIC_URL}/js/script.js`
This solution worked for me
React.component then you need to use componentDidMount() (before render), this is required as hooks work inside a function component or custom hooks only.Small Snippet of the code :
import React, from "react";
React.useEffect(() => {
const LoadExternalScript = () => {
const externalScript = document.createElement("script");
externalScript.onerror = loadError;
externalScript.id = "external";
externalScript.async = true;
externalScript.type = "text/javascript";
externalScript.setAttribute("crossorigin", "anonymous");
document.body.appendChild(externalScript);
externalScript.src = './script.js';
};
LoadExternalScript();
return () => {
// document.body.removeChild(externalScript);
};
}, []);
You will find this link useful if you get a syntax error:
"Uncaught SyntaxError: Unexpected token < in React" Syntax error solution