How to Add External Scripts from a Block

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.

1. Locate Your Block's 'componentDidMount' Function

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.

2. Use the 'addScript' Block Util

this.props.addScript('https://cdn.domain.net.script.min.js')

3. Protect the Script from Loading When It Shouldn't

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')
}

Further Reading

See "Block Utils" for optional addScript arguments and more information about isAmpRequest and isRendering.