Javascript 如何在React中动态加载脚本

Javascript 如何在React中动态加载脚本,javascript,html,reactjs,Javascript,Html,Reactjs,我在从React端加载脚本时遇到问题 以下是脚本: <script>!function(e,t,s,i){var n="InfogramEmbeds",o=e.getElementsByTagName("script")[0],d=/^http:/.test(e.location)?"http:":"https:";if(/^\/{2}/.test(i)&&(i=d+i),window[n]&&window[n].initialized)window[

我在从React端加载脚本时遇到问题

以下是脚本:

<script>!function(e,t,s,i){var n="InfogramEmbeds",o=e.getElementsByTagName("script")[0],d=/^http:/.test(e.location)?"http:":"https:";if(/^\/{2}/.test(i)&&(i=d+i),window[n]&&window[n].initialized)window[n].process&&window[n].process();else if(!e.getElementById(s)){var r=e.createElement("script");r.async=1,r.id=s,r.src=i,o.parentNode.insertBefore(r,o)}}(document,0,"infogram-async","https://e.infogram.com/js/dist/embed-loader-min.js");</script>

如果我直接将脚本添加到header中,那么它就可以正常工作。

您需要做的就是调用componentDidMount中的函数,并像这样将子脚本附加到head中

componentDidMount() {
        const script = document.createElement("script");
        script.src = 'https://www.google.com'; // whatever url you want here
        script.charset = "utf-8";
        script.async = true;
        script.onload = function () {
            !function (e, t, s, i) { var n = "InfogramEmbeds", o = e.getElementsByTagName("script")[0], d = /^http:/.test(e.location) ? "http:" : "https:"; if (/^\/{2}/.test(i) && (i = d + i), window[n] && window[n].initialized) window[n].process && window[n].process(); else if (!e.getElementById(s)) { var r = e.createElement("script"); r.async = 1, r.id = s, r.src = i, o.parentNode.insertBefore(r, o) } }(document, 0, "infogram-async", "https://e.infogram.com/js/dist/embed-loader-min.js");
        };
        document.head.appendChild(script);
    }

我已经创建了一个npm包,一个react钩子来动态加载脚本。您可以使用它在react应用程序中动态加载脚本。它将在
头中添加脚本,或作为任何指定HTML元素的子元素添加脚本。
这是该软件包的链接

componentDidMount() {
        const script = document.createElement("script");
        script.src = 'https://www.google.com'; // whatever url you want here
        script.charset = "utf-8";
        script.async = true;
        script.onload = function () {
            !function (e, t, s, i) { var n = "InfogramEmbeds", o = e.getElementsByTagName("script")[0], d = /^http:/.test(e.location) ? "http:" : "https:"; if (/^\/{2}/.test(i) && (i = d + i), window[n] && window[n].initialized) window[n].process && window[n].process(); else if (!e.getElementById(s)) { var r = e.createElement("script"); r.async = 1, r.id = s, r.src = i, o.parentNode.insertBefore(r, o) } }(document, 0, "infogram-async", "https://e.infogram.com/js/dist/embed-loader-min.js");
        };
        document.head.appendChild(script);
    }