Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
How come my external JS file won't load in ReactJS?

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.

Here is the file structure: enter image description here

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>
about 4 years ago · Juan Pablo Isaza Relatório

0

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`

about 4 years ago · Juan Pablo Isaza Relatório

0

This solution worked for me

  1. I used useEffect hook inside a function component (before return). This can be used inside App.js also before return. Note: if you want to do this inside a class which extends React.component then you need to use componentDidMount() (before render), this is required as hooks work inside a function component or custom hooks only.
  2. In the header add a script tag
  1. 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);
      };
    }, []);
    
  2. You will find this link useful if you get a syntax error:

"Uncaught SyntaxError: Unexpected token < in React" Syntax error solution

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda