我在 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>
我尝试过这样的事情:
const script = document.createElement("script");
script.src = scriptUrl;
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.body.appendChild(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);
}
关于javascript - 如何在React中动态加载脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55124736/