本文介绍了HTML脚本正在加载AFTER反应组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的index.html

My index.html

<!DOCTYPE html>
<html lang="en">
    <head>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="google-signin-client_id" content= "my_client_id.apps.googleusercontent.com">

        <meta name="google-signin-scope" content="profile email">
        <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
        <script>
            function start() {
                console.log('script running')
                gapi.load('auth2', function() {
                    auth2 = gapi.auth2.init({
                        client_id: 'my_client_id.apps.googleusercontent.com',
                        scope: 'profile email'
                    });
                });
            }
        </script>
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>


  </body>
</html>

start()函数中我打印到控制台查看它何时运行。

In the start() function I print to the console to see when it's running.

当我加载页面时,每隔一段时间 start()将会在反应组件之后加载

When I load the page, every so often start() will load after the react components.

Login.js

    componentDidMount() {
        console.log(gapi.auth2.getAuthInstance())
    }

在调试器中你可以看到脚本在组件之后加载:

In the debugger you can see that the script is loading after the component:

如果我刷新页面几次,它可以正常工作。但有时它会起作用,有时则不然。

If I refresh the page a few times, it works fine. But sometimes it works, sometimes it doesn't.

为什么?

推荐答案

我认为在反应中加载脚本的最佳方法是使用容器组件。它是一个非常简单的组件,它允许您编写用于在组件而不是index.html中导入脚本的逻辑。您还要确保在检入componentDidMount后通过调用loadScript多次不要包含脚本。

I think the best way to load scripts in react is with a container component. It's a pretty simple component and it allows to you write the logic for importing the script in a component rather than your index.html. You are also going to want to make sure you don't include the script more than once by calling loadScript after a check in componentDidMount.

这改编自:

这样的事情。 。 。

  componentDidMount() {
    if (!window.google) {
      this.loadMapScript();
    }
    else if (!window.google.maps) {
      this.loadMapScript();
    }
    else {
      this.setState({ apiLoaded: true })
    }
  }

  loadMapScript() {
    // Load the google maps api script when the component is mounted.

    loadScript('https://maps.googleapis.com/maps/api/js?key=YOUR_KEY')
      .then((script) => {
        // Grab the script object in case it is ever needed.
        this.mapScript = script;
        this.setState({ apiLoaded: true });
      })
      .catch((err: Error) => {
        console.error(err.message);
      });
  }

  render() {
    return (
      <div className={this.props.className}>
        {this.state.apiLoaded ? (
          <Map
            zoom={10}
            position={{ lat: 43.0795, lng: -75.7507 }}
          />
        ) : (
          <LoadingCircle />
        )}
      </div>
    );
  }

然后在另一个文件中:

const loadScript = (url) => new Promise((resolve, reject) => {
  let ready = false;
  if (!document) {
    reject(new Error('Document was not defined'));
  }
  const tag = document.getElementsByTagName('script')[0];
  const script = document.createElement('script');

  script.type = 'text/javascript';
  script.src = url;
  script.async = true;
  script.onreadystatechange = () => {
    if (!ready && (!this.readyState || this.readyState === 'complete')) {
      ready = true;
      resolve(script);
    }
  };
  script.onload = script.onreadystatechange;

  script.onerror = (msg) => {
    console.log(msg);
    reject(new Error('Error loading script.'));
  };

  script.onabort = (msg) => {
    console.log(msg);
    reject(new Error('Script loading aboirted.'));
  };

  if (tag.parentNode != null) {
    tag.parentNode.insertBefore(script, tag);
  }
});


export default loadScript;

我知道这很多但是当我第一次这样做的时候,当我发现那里时它是如此松了一口气是一种(相当)简单的方法,可以在任何反应组件中包含任何脚本。

I know it's a lot but when I was first doing this it was so relieving when I found out there was a (fairly) simple way of including any script in any react component.

编辑:其中一些我只是复制粘贴,但如果你不使用create-react -app你可能不得不替换一些ES6语法。

Some of this I just copy pasted but if you aren't using create-react-app you will probably have to replace some of the ES6 syntax.

这篇关于HTML脚本正在加载AFTER反应组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 19:17