在动态添加脚本之前,正在执行动态添加的脚本

问题描述 投票:-1回答:1

我有一个HTML页面,它向其他域中托管的反应页面发出请求。有一次,我得到页面响应,我将JS从请求页面的主题部分复制到我的页面的主题部分,并在主体部分中提供相同的脚本。

请求页面是一个反应页面,其中包含head部分中的react和react-dom以及body部分中的其他JS块,它将复制到我页面上的相同部分。

我想,任何复制到页面头部的脚本都会立即阻止页面执行,一旦脚本中的所有脚本都被执行,那么只有正文中的脚本才会执行。

我得到间歇性的客户端错误“ReactDOM未定义”。似乎脚本复制到body正在执行脚本之前执行脚本。

ReactJS和ReactDOM JS位于页面的头部和块中,其中抛出错误在体内。

external "ReactDOM":1 Uncaught ReferenceError: ReactDOM is not defined
    at Object.faye (external "ReactDOM":1)
    at f (bootstrap:83)
    at Module.7n5H (tes1.ts:18)
    at f (bootstrap:83)
    at Object.0 (test2.ts:114)
    at f (bootstrap:83)
    at t (bootstrap:45)
    at Array.r [as push] (bootstrap:32)
    at 0.9efbe0e7cdf36824.chunk.js?_=1555361723703:1 faye @ external "ReactDOM":1 f @ bootstrap:83 7n5H @ tes1.ts:18 f @ bootstrap:83 0 @ test2.ts:114 f @ bootstrap:83 t @ bootstrap:45 r @ bootstrap:32 (anonymous) @ 0.9efbe0e7cdf36824.chunk.js?_=1555361723703:1
reactjs react-dom
1个回答
0
投票

这很简单,它与头部和体内的代码没有关系,获取反应文件的调用有点慢,所以它没有及时让你的代码在体内使用它因此它是未定义的

防爆。问题

// this is the we will put in the body 
// log the react object to the console simple
let body = "console.log(React)"

// im using a button to make it easier to understand
document.querySelector('input').onclick = () => {


  // here we are assing a scrupt tag to the head
  // with the link to the react lib
  let headscript = document.createElement('script');
  headscript.src = "https://unpkg.com/react@15/dist/react.js"
  document.querySelector('head').appendChild(headscript);


  // and here we are logging the React object
  // from the body
  let bodyscript = document.createElement('script');
  bodyscript.innerHTML = body;
  document.querySelector('body').appendChild(bodyscript);
};
Click once and wait a bit then click again
<br>
<input type="button" value="click me">

正如您所看到的,这只是异步操作的老问题,解决方案是使用promises。

演示

let body = "console.log(React)"
document.querySelector('input').onclick = () => {
  // request to get the code
  fetch("https://unpkg.com/react@15/dist/react.js")
    // returning it as plain text because that what it is
    .then(response => response.text())
    .then(data => {
      // same as before
      let headscript = document.createElement('script');
      headscript.innerHTML = data;
      document.querySelector('head').appendChild(headscript);

      // and because all code inside the reac lib is not async
      // this is safe to call right after
      let bodyscript = document.createElement('script');
      bodyscript.innerHTML = body;
      document.querySelector('body').appendChild(bodyscript);
    })
};
<input type="button" value="click me">
© www.soinside.com 2019 - 2024. All rights reserved.