Ad

Async Loading Script Within React Component

- 1 answer

I have a problem loading external script within 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>

and here is my render function where i would like to have the javascipt load asyn, it's super easy in a html file, however i am stunned within a react component on how to do acheive. (If i can avoid install another external module would be best). Many thanks

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

Answer

dangerouslySetInnerHTML is the solution i have found.

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

This allow you to have script tag and insert JavaScript in side of jSX.

Ad
source: stackoverflow.com
Ad