How to load script in react component

前端 未结 5 1851
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 16:45

I am having following script file



        
5条回答
  •  盖世英雄少女心
    2020-12-29 17:14

    the following method is worked for me. try, hope it will work for you. basically, you can create a script tag and append it to the body tag. like this--

    var tag = document.createElement('script');
    tag.async = true;
    tag.src = 'THE PATH TO THE JS FILE OR A CDN LINK';
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(tag);
    

    you can use this on a life cycle hook of react like this.

    componentDidMount() {
        var loadScript = function (src) {
          var tag = document.createElement('script');
          tag.async = false;
          tag.src = src;
          var body = document.getElementsByTagName('body')[0];
          body.appendChild(tag);
        }
    
        loadScript('PATH TO THE JS FILE OR CDN URL');
      }
    

提交回复
热议问题