In this how-to guide, we will be going over how to add external scripts, such as Javascript files or CSS, from within a block.
Open up Block.js and locate the componentDidMount or constructor function. If those functions don't exist yet, add the appropriate one to your component. You may need to refactor the block to use class syntax.
this.props.addScript('https://cdn.domain.net.script.min.js')
There are times when you may not want the script to load; for example, in Site Designer, a unit test, or an AMP request. Add a condition around the code above to restrict when it loads.
if (
!this.props.isAmpRequest &&
!this.props.isRendering &&
typeof window === 'undefined'
) {
this.props.addScript('https://cdn.domain.net.script.min.js')
}
See "Block Utils" for optional addScript arguments and more information about isAmpRequest and isRendering.