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.