react组件中的异步加载脚本

IT技术 reactjs
2021-05-17 15:50:29

我在 react JSX 中加载外部脚本时遇到问题

<script>
    (function(d) {
        var config = {
                kitId: 1234567,
                scriptTimeout: 3000,
                async: true
            },
            h=d.documentElement,t=setTimeout(function(){h.className=h.className.replace(/\bwf-loading\b/g,"")+" wf-inactive";},config.scriptTimeout),tk=d.createElement("script"),f=false,s=d.getElementsByTagName("script")[0],a;h.className+=" wf-loading";tk.src='https://use.typekit.net/'+config.kitId+'.js';tk.async=true;tk.onload=tk.onreadystatechange=function(){a=this.readyState;if(f||a&&a!="complete"&&a!="loaded")return;f=true;clearTimeout(t);try{Typekit.load(config)}catch(e){}};s.parentNode.insertBefore(tk,s)
    })(document);
</script>

这是我的渲染函数,我想让 javascipt 加载异步,它在 html 文件中非常简单,但是我在react组件中对如何实现感到震惊。(如果我可以避免安装另一个外部module最好)。非常感谢

render() {
    return (
        <head>
            //Script to load asyn
        </head>
    )
}
2个回答

我的服务器呈现初始 HTML 文档,所以我不能像@mjhm 建议的那样将它插入头部。使用@bluebill1049 的回答,我能够使用 ES6 模板字符串并做出reactdangerouslySetInnerHTML

import React, {Component} from 'react';

export default class Html extends Component {

  render() {
    const loadTypeKit = `
      (function(d) {

        var config = {
            kitId: 'YOUR_KITID', 
            scriptTimeout: 3000, 
            async: true
          },
          h=d.documentElement,
          t=setTimeout(function() {
            h.className=h.className.replace(/wf-loading/g,"")+" wf-inactive";
          },config.scriptTimeout),
          tk=d.createElement("script"),
          f=false,
          s=d.getElementsByTagName("script")[0],
          a;

        h.className+=" wf-loading";
        tk.src='https://use.typekit.net/'+config.kitId+'.js';
        tk.async=true;
        tk.onload=tk.onreadystatechange=function() {
          a=this.readyState;
          if(f||a&&a!="complete"&&a!="loaded") return;
          f=true;
          clearTimeout(t);
          try{
            Typekit.load(config)
          } catch(e){ }
        };
        s.parentNode.insertBefore(tk,s);

      })(document);
      `;

    return (
      <html>
      <head>
        <script dangerouslySetInnerHTML={{__html: loadTypeKit}} />
      </head>
      <body>
          ...
      </body>
      </html>
    );
  }
}

risklySetInnerHTML是我找到的解决方案。

https://facebook.github.io/react/tips/dangerously-set-inner-html.html

这允许您拥有脚本标记并在 jSX 中插入 JavaScript。