Skip to content

How I load external JavaScript Libraries in a Ghost theme

This post was my reply to a Ghost Forum question about loading an external JavaScript library in a Ghost theme. I will show different ways to load a script, the difference between each one, and the method I use in my Ghost themes.

Loading From CDN

Adding the CDN should be enough. The CDN line first; then, you can reference and run the script after. The order is essential.

<script src="https://unpkg.com/typewriter-effect@latest/dist/core.js"></script>
<script>
  var app = document.getElementById('app');
  // ...
</script>

The issue here is that if you have more than one library, you will need to include them in the theme template file, and you will end up with many file requests, which is bad for site performance.

Loading From node_modules

Also, adding the library from the installed node_modules directory will work. Both ways load the exact file (core.js).

<script src="node_modules/typewriter-effect/dist/core.js"></script>
<script>
  var app = document.getElementById('app');
  // ...
</script>

In addition to the same previous issue, the issue here is that you will need to include the node_modules directory with your theme final zip file. You only need one file, and you will have a large theme size.

Here Is How I Do It

Here is what I do. I use Gulp to include and compile all the third-party libraries plus my theme JS file (/assets/js/app.js), where I run and use these libraries into a single file.

1.

I install the library with npm and save it to the package.js file.

npm i typewriter-effect --save

2.

Add the library to the gulpfile.js file JavaScript task. Here is a simplified example.

  gulp.task('js', function(done) {
    return gulp.src([
      './node_modules/typewriter-effect/dist/core.js',
      './assets/js/app.js'])
      .pipe(concat('app.js'))
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest('./assets/js'))
      done();
  });

I will have the app.min.js file by running this task, which I add to the theme default.hbs file.

<script src='{{ asset 'js/app.min.js' }}'></script>

I have another task to zip the theme, which will exclude the node_modules directory.

gulp.task('zip', function () {
  return gulp.src([
    './**',
    '!node_modules/**',
    '!bower_components/**',
    '!.git/**',
    '!.DS_Store'
  ], { dot: true })
  .pipe(zip('beirut.zip'))
  .pipe(gulp.dest('../'))
  done();
});

Here is a complete example of the gulpfile.js.

tutorials

Latest Ghost Themes