【问题标题】:Async loading script within react component反应组件中的异步加载脚本
【发布时间】:2018-06-14 02:52:18
【问题描述】:

我在 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 文件中非常容易,但是我对如何实现的反应组件感到震惊。 (如果我可以避免安装另一个外部模块最好)。非常感谢

render() {
    return (
        <head>
            //Script to load asyn
        </head>
    )
}

【问题讨论】:

  • 您尝试执行的操作不起作用。而是在 componentDidMount() stackoverflow.com/questions/13121948/… 中尝试以下策略之一
  • 在你的 html 中注入的 react 组件在哪里?
  • 是的,我不清楚您要做什么。你能提供一个你的实现不起作用的小提琴吗?

标签: reactjs


【解决方案1】:

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

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>
    );
  }
}

【讨论】:

    【解决方案2】:

    dangerouslySetInnerHTML 是我找到的解决方案。

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

    这允许你有脚本标签并在 jSX 中插入 JavaScript。

    【讨论】:

    • 如果您使用您使用的实际解决方案更新您的特定代码示例,那就太好了。无论如何感谢您的指针。
    猜你喜欢
    • 1970-01-01
    • 2019-01-05
    • 2011-12-04
    • 1970-01-01
    • 2018-09-25
    • 2019-02-01
    • 1970-01-01
    • 2016-07-09
    • 2012-10-01
    相关资源
    最近更新 更多