How to run scripts in index.html in react if you don't have index.html

2.3k Views Asked by At

I am still new to React. I have React web App to which I need to add several scripts. Although scripts have to be inside of body tag in index.html. Like this :

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>React example</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style media="only screen">
      html,
      body,
      #root {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="root">Loading React example&hellip;</div>
      <script 
        src="https://unpkg.com/[email protected]/dist/system.src.js"
       > 
       </script>
      <script src="systemjs.config.js"></script>
      <script>
        System.import('./index.jsx').catch(function(err) {
          console.error(err);
        });
      </script>
  </body>
</html>

But the problem is that my app doesn't have index.html it has only index.js. I tried to add this script with document.write but I think it's a wrong way of doing it. Besides that i have Semantic and Syntactic errors which I cannot understand they are also attached here

2

There are 2 best solutions below

2
Judith Hartmann On BEST ANSWER

You can append the scripts in your react code with:

let script = document.createElement("script");
script.setAttribute("src", scriptUrl);
script.setAttribute("type", "text/javascript");

(this is for linked scripts, but embedded scripts can be done in a similar way)

0
Renderlife On

Hi I used this in my react application I inserted dynamic yandex metrica code

Возможно поможет кому то вставить код Яндекс метрики в SPA ReactJs App динамически, код счетчика я получаю с бекенда

export function addCustomScriptAndHtmlInHead(tagString: string ): void {
    const range = document.createRange()
    range.selectNode(document.getElementsByTagName('BODY')[0])
    const documentFragment = range.createContextualFragment(tagString)
    document.head.appendChild(documentFragment)
}