Automating Google Pagespeed Optimization with Gulp

In this article, we’re going to look at how to use the popular task runner Gulp, in order to optimize your website’s loading speed and leverage your Google Pagespeed rating. Before you start, you’re going to need NodeJS installed. If you don’t have it already, simply follow the link.

What is GulpJS?

GulpJS is a javascript task runner built on NodeJS, that allows you to automate your development tasks such as compiling sass code to CSS, automating your build cycle, automating page optimization, and more. Because it uses NodeJS, it’s easily modifiable to add and remove tasks to build your own custom build/optimization cycle, requiring you only to include your dependencies and piping the source files through (You’ll see what this means in a moment).

Chapter 1 – Setting up Your Project

Step 1 – Creating the src directory

If you’re starting from an existing website, you’re going to need to move a few files and folder around to make it easily readable for Gulp. Go ahead and take your current project files and move them into a new directory titled src (as in source code). This will let Gulp know that this is the code that needs to be optimized throughout the cycle, and will keep it separated from your final build code. If you don’t have a pre-existing project, then go ahead and create the folders sass, js, and assets in your src folder, as well as an index.html file.

Step 2 – Creating the build directory

Now that you’ve created your src folder, creating the corresponding build folder is actually quite easy. Since GulpJS handles build scaffolding for you based on the directions you give in the gulpfile (gulpfile.js), all that’s needed for this step is creating a folder titled build at the same level as the src folder, and GulpJS will generate all the inner folders and files for you once you run it.

Step 3 – Creating your package.json

Now that we’ve added some substance to our application, we’re ready to initialize our project with Node. Go ahead and open your terminal of choice to your project direction and run

npm init

This command will guide you through a series of questions about your project so that node.js can describe your node package in the package.JSON file.

Step 4 – Install Project Dependencies

Now that the package.json is created, we now have the flexibility to establish other node packages as project dependencies, so let’s do that now. Go ahead and run the command

This will install not only gulp, but all of the gulp packages required for our build cycle as well. You’ll find these packages to be some of the more common packages used in gulp file, and you’ll learn a little bit more about what these packages each do in just a moment. Also, by including the –-save-dev flag in your npm install command, you’re marking those packages as project dependencies so your project will be lightweight and manageable if you use git. If you’re new to NodeJS and want to take advantage of git, you can use the NodeJS .gitignore template found here as well.

Chapter 2 – Creating your gulpfile

Step 1 – Including the project dependencies

First, go ahead and create your gulpfile (gulpfile.js) at the root of your project directory. This is the file Gulp will use to determine which tasks to run, where to get the source code, and where to place the build code. Once you’ve created the build code, we’re going to start by placing the following lines of code at the top of your file.

I’ve commented the code above to let you know what each package is going to be used for, and if you want to add any more packages to your cycle this is where you’d do that.

Step 2 – Creating the default task

gulp.task('default', ['html', 'sass', 'js', 'images', 'watch']);

With GulpJS, it uses the default task to determine which tasks to run in which order. As you can see, it’s tasks parameter can be used in array form, but just like any other gulp task, you can also use a function. For our use, we’ll use an array since we have a list of tasks that Gulp needs to run on start. Go ahead and add the above code into your gulpfile as well.

Step 3 – Creating the HTML task

gulp.task('html', function() {
});

Now that we’ve created our default task, we’re ready to get going with Gulp by creating our first real task. Go ahead and create a task called HTML using the code above.

Step 4 – Changing gulp task source

Now that we have the task created, let’s go ahead and get our source files. To do this, start off by adding the code below into the HTML task function.

return gulp.src('./src/**/*.html')

This allows us to get the files in the application for manipulation. Now that we’ve requested the source from gulp, we’re going to want to ensure it’s grabbing the right files from the right location. In gulp, there are a few rules to remember when it comes to getting source files. The string ** means any folder in directory, and *.ext would mean any file with said file extension in the directory (ex: *.html for HTML, *.js for javascript, etc.), and * means any file in the directory.

This is important to understand because as you add more files to your project, you’re not going to want to manually add every file in as a source, you want to use the wildcards we just discussed to automate that process. Now that you understand how GulpJS looks for its source files, let’s set the source for our HTML task. Inside the src function of the gulp variable in the line of code above, go ahead and erase the string currently inside and replace it with the location of your src (which unless you had a pre-existing website, it will be the same as above).

Step 5 – Piping the HTML through the minifier

Now that we’ve established our task and task source, we’re ready to pipe our code through the HTML minifier we previously included and out to the build destination. Go ahead and add the code above to the HTML task. Notice that we’re using a new function named pipe. The pipe is a GulpJS function designed to send your source code through another GulpJS function and then output the result. Notice how we pipe our source code through the htmlmin function, declare our options with JSON inside of said function, and then we take the finished code and pipe it out to it’s destination in the build folder. This location will also need to be changed based on where you want it to output. Now that your HTML task is done, it should look like this.

Step 7 – Compiling and minimizing our SASS

Now, add the above code to your Gulp task as created previously. In this code, you’ll see that we use a few different functions to transform our SASS into clean optimal CSS. First, we’re going to pipe our code through the concat function to join all of our CSS files together into one file named all.sass. Next, we take our concatenated file and pipe it through a sass compiler, setting the indented syntax option to true (just a personal preference. Since the SASS compiler throws errors, we’ve also attached a way to handle those errors rather than the default exit. Next, we’re going to minimize our code and set the compatibility setting to ie8 and above, and pipe it out to its destination in its build directory.

Now, we’re going to create our critical CSS task. Critical CSS is the inlined CSS required to load the before-the-fold section of the page, that allows you to load your page much quicker. Make sure you set your base (the base destination to look for files in), your HTML source, your CSS source, your HTML destination, and your dimensions. I went ahead and used a few of the most relevant screen resolutions, but this is all at your discretion.

Step 9 – Creating the JS task

gulp.task('js', function() {
return gulp.src('./src/js/**/*.js')
});

As we’ve done several times before now, we’re going to create a new Gulp task named js. Make sure you set the source location properly again, or else you’ll run into errors on run.

Step 10– Compiling and concatenating our JavaScript

Now, go ahead and add the code above to your JS task, again concatenating our code into one file, and then minifying it and piping it out to its build destination. Make sure to set your build location properly again, and remember to set your HTML to use the concatenated file name, and not the original as well.

Step 11 – The Images Task

Finally, we’re creating one last task before we move onto our watch task. To begin, you’re going to want to head over to https://tinypng.com/ and pick up a developer API key. This will allow you to automatically optimize your images, fixing load times and heavily boosting your Google Pagespeed Score. Next, use the code above to add the images task into your Gulpfile, ensuring to accurately fill out the source and build destinations, as well as the API key.

Now we’re going to progress onto our watch task. A Gulp watch task should be run at the end of the default task cycle as defined in the array we discussed earlier and is use to watching your files for changes in order to automate the build process. Go ahead and add the code above into your Gulpfile now, ensuring to replace the task sources with the corresponding source for each task you used earlier.

Now that our gulpfile is completed, overview it to ensure that all source and build directories are correct, as well as that your API key is entered correctly. Once this is done, you can run your gulpfile by going into the root of your project directory in the terminal and simply type gulp and watch the magic happen! Your clean and finished project to upload and use is now available in the build folder.

Step 2 – Further Pagespeed Optimization

Now that our page is minimal and optimized to Google’s standards, you’ll notice a dramatic increase in your Google Pagespeed Insight rating. Although this does dramatically increase your rating it’s definitely not all you needed to score that much craved 100 on Google Pagespeed insights. If you’re interested in learning more about how to increase your rating in Google Pagespeed insights, you can learn more here.

Feel free to share your achievements and your Google PageSpeed Scores! We will love to see it.

Have you enjoyed this article? If so, supports us by sharing this article or Become a Patron!