DEV Community

Robert Marshall
Robert Marshall

Posted on • Originally published at robertmarshall.dev on

Adding Google Adsense to Gatsby Website


This article was originally posted (and is more up to date) at https://robertmarshall.dev/blog/adding-google-adsense-to-gatsby-website/


There are several plugins that have popped up that say they can add Google AdSense to a Gatsby site. However these only get you part of the way there.

Unfortunately as much as Google says that AdSense is lightweight and that they defer the load until after the page has loaded โ€“ this is not true. I needed a solution which would not effect my page speed, but also load the ads when they were needed. I decided to only load Google Ads on scroll.

Disclaimer: This solution slightly impair Google Ads above the fold. They will be loaded once the user scrolls the page. I personally do not like displaying third party ads above the fold, as this massively impacts page speed.

How to add Google AdSense to a Gatsby Website?

To add Google AdSense to our Gatsby website we need to do two things

  1. Add the Google AdSense JavaScript code to all pages of the Gatsby Website
  2. Create a component which will create a place for the Google ads to be injected into

Add Google AdSense JavaScript code to Gatsby

I created a global Layout component which wraps my whole website. However as long as this component is used on every page of your Gatsby site it doesnโ€™t matter where it is placed. You could even turn the specific piece of code if you wanted, and inject it that way.

This code works by waiting for the page to render, then waiting for the user to scroll before injecting the Google AdSense code. In essence, lazy loading the Google AdSense script without any overheads.

The code for adding the Google AdSense script looks like this:

import React, { useRef } from 'react'
const Layout = () => {
    const scrolled = useRef(null)

    useEffect(() => {
        const headID = document.getElementsByTagName('head')[0]

        document.addEventListener('scroll', function (e) {
            if (!scrolled.current) {
                scrolled.current = true

                // Google Ads
                const gaScript = document.createElement('script')
                gaScript.async = true
                gaScript.crossorigin = 'anonymous'
                gaScript['data-ad-client'] = 'YOUR-CODE-HERE'
                gaScript.src =
                    'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'
                gaScript.type = 'text/javascript'
                headID.appendChild(gaScript)
            }
        })
    }, [])
}

export default Layout
Enter fullscreen mode Exit fullscreen mode

Remember to swap out YOUR-CODE-HERE for your Google AdSense code.

This code has added Google AdSense to your site, but it still needs to know where to display the ads!

Create the Google AdSense Ad Block Component

Creating the component to hold the actual Google Ad is a fairly simple process. I created a component called AdBlock and use the react-adsense package to get me over the line.

Firstly install react-adsense using either:

  • npm install react-adsense
  • yarn add react-adsense

Once installed it can be implemented into a component like so:

import React from 'react'
import AdSense from 'react-adsense'

const AdBlock = () => (
    <AdSense.Google
        client="YOUR-CODE-HERE"
        slot="YOUR-SLOT-HERE"
        style={{ display: 'block' }}
        layout="in-article"
        format="fluid"
    />
)

export default AdBlock
Enter fullscreen mode Exit fullscreen mode

Once you have updated YOUR-CODE-HERE and YOUR-SLOT-HERE to your specific information, this component is good to be used in your Gatsby website.

Remember now Google AdSense has been added to your Gatsby website, you are also required to include a Cookie banner for EU law.

Top comments (0)