add third-party js library to Create React App

邮差的信 提交于 2019-12-10 15:26:13

问题


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.



来源:https://stackoverflow.com/questions/49796861/add-third-party-js-library-to-create-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!