add third-party js library to Create React App

2019-07-06 23:18发布

问题:

I am using chartIQ library in my Create React App. I added it just by using script tag in my index.html file <script src="chartiq/js/chartiq.js"></script> and it works that way, but it does not feel right. Because I need this library only for one component and it would be better to import somehow this library only to this component. Is there any way to do this correcly?

回答1:

You can use it in the following way:

function loadScript(url, callback){

    let script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

and then use this function on componentDidMount() to load the external script.