2

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.

2 Answers 2

3

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

But then how do you add use it ? Like how do you import the function inside the library to your components ?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.