gpt4 book ai didi

javascript - 响应组件后加载 HTML 脚本

转载 作者:太空狗 更新时间:2023-10-29 15:53:18 25 4
gpt4 key购买 nike

我的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() 函数中,我打印到控制台以查看它何时运行。

当我加载页面时,start() 会经常加载 React 组件之后

登录.js

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

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

enter image description here

如果我刷新页面几次,它工作正常。但有时有效,有时无效。

为什么?

最佳答案

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

本文改编自:https://www.fullstackreact.com/articles/how-to-write-a-google-maps-react-component/

是这样的。 . .

  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;

我知道它有很多,但当我第一次这样做时,当我发现有一种(相当)简单的方法可以将任何脚本包含在任何 React 组件中时,我感到非常欣慰。

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

关于javascript - 响应组件后加载 HTML 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47421602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com