Asynchronous script loading inside a responsive component

I have a problem loading an external script inside a JSX reaction

<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> 

and here is my rendering function, where I would like to have javascipt load asyn, it is very simple in the html file, however, I am stunned inside the react component on how to make acheive. (If I can avoid installing another external module, it would be better). Thank you very much

 render() { return ( <head> //Script to load asyn </head> ) } 
+2
source share
2 answers

dangerouslySetInnerHTML is the solution I found.

https://facebook.imtqy.com/react/tips/dangerously-set-inner-html.html

This allows you to have a script tag and embed JavaScript in the jSX side.

+1
source

My server displays the original HTML document, so I couldn’t just insert it into my head, as @mjhm suggested. Using the @ bluebill1049 answer, I was able to use ES6 template templates and reacted 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
source

Source: https://habr.com/ru/post/1259277/


All Articles