2

I'm trying to load external javascript (https://github.com/spite/ccapture.js) to my React.js component.

Currently the code looks like this:

let aScript = document.createElement('script');
aScript.type = 'text/javascript';
aScript.src = "CCapture.min.js";
document.head.appendChild(aScript);

This code correctly appends script to the page (checked the HTML). But now I'm wondering how can I use the contents of the script in a constructor function. Specifically, per the documentation - it would look something like this..

var capturer = new CCapture({
    framerate: 60,
    verbose: true
});

The error I'm getting says the CCapture is not defined. Am I missing something here? Not sure how to pull from the library itself.

I've added a function to make sure it is loading before the function itself runs per this instruction, https://stackoverflow.com/a/42848407/8497330.

I'm also not using the npm package because it does not work for the 'webm' format. Looking for a bandaid while the npm package is corrected.

Faye Hayes
  • 263
  • 3
  • 13

2 Answers2

1

First of You should load your script asynchronously. For instance, you can use this gist: loadScript. This loadScript function returns a promise which you can use to wait for your library to load. Secondly, you should not put your code inside the constructor and instead in the componentDidMount like this

componentDidMount () {
    loadScript('CCapture.min.js')
      .then(() => {
        var capturer = new CCapture({
          framerate: 60,
          verbose: true
        });
      })
      // you can even handle the loading error for your script
      .catch((error) => {
        console.log('Error when loading CCapture.min.js: ', error);
      });
}

In cae you need it you could aslo save the capturer instance in your component state (using this.setState({capturer})) or directly inside the instance object of your component like this.capturer = capturer;

Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
0

The most likely cause is that the script hasn't been loaded and evaluated by the browser before you're making your call. The is an excellent (and detailed) description of what is happening in this Answer: https://stackoverflow.com/a/14786759/105518

In my experience, the last piece of advice in that answer is generally the least painful to implement: leverage JQuery's getScript function. It handles wiring up all the bits for you:

$.getScript("CCapture.min.js", function () {
    const capturer = new CCapture({
        framerate: 60,
        verbose: true
    });
});
Marc LaFleur
  • 31,987
  • 4
  • 37
  • 63