In this example, we'll add an external script to a mod.

1. Start with a blank mod

Create or clone a blank mod to get started.

2. Add some JavaScript that relies on an external library

Let's add a Google Charts Pie Chart to our mod -- doing so will require that we add the script for this library. Add the following to your mod's JavaScript:

google.charts.load('current', { 'packages': ['corechart'] })
google.charts.setOnLoadCallback(drawChart)

function drawChart() {
  const data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work',     11],
    ['Eat',      2],
    ['Commute',  2],
    ['Watch TV', 2],
    ['Sleep',    7]
  ])

  const options = { title: 'My Daily Activities' }
  const chart = new google.visualization.PieChart(mod.el)
  chart.draw(data, options)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Without the external library, the console will throw an error and nothing shows because google is not defined.

3. Add an external script

Click the gear (cog) in the header of the JS panel to open the mod's JavaScript settings. From there, you can either choose a script from the dropdown menu or paste a URL to other scripts.

Paste the URL for the Google Charts script: https://www.gstatic.com/charts/loader.js

Now when our mod runs, the JavaScript will function properly, and we get a nice Pie Chart:

TIP

See the mod from this example here

4. Add script tags to your page (optional)

Your mod will automatically load any external scripts when you've added the mod tag to your page.

However, for improved performance, it is best to also add any external script tags to your page as described in Optimizing CSS & JS assets.

Last Updated: 10/5/2018, 6:32:35 PM