Mizlul
Mizlul

Reputation: 2290

How to dynamically load script in React

I am having problem loading a script from within React side

This is the script:

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

I tried something like this:

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

If I add the script directly into header than it works perfectly fine.

Upvotes: 2

Views: 10421

Answers (2)

Eesa
Eesa

Reputation: 2859

I have created an npm package, a react hook to load a script dynamically. You can use that to load script dynamically in your react application. It will add script in the head or as child of any specified HTML element. Here is the link to the package https://www.npmjs.com/package/use-script-loader

Upvotes: 0

Rishabh Rawat
Rishabh Rawat

Reputation: 859

All you need to do is call the function inside componentDidMount and append the child into head like this

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

Upvotes: 3

Related Questions