Nuxt Lazy Load Google Adsense When Component/Element Is Visible

April 12, 2022

Modify from Nuxt Load Google Adsense Auto Ads.

Install

npm install --save vue-observe-visibility

Edit components/GoogleAd.vue

<template>
  <component v-if="isShow" :class="_class" :is="tag" v-observe-visibility="{ callback: visibilityChanged, intersection: { rootMargin: '50px' }, once: true, }">
    <ins v-if="type == 'link'"
      class="adsbygoogle"
      style="display:block"
      :data-ad-channel="channel"
      data-ad-format="fluid"
      data-ad-layout-key="-gb+7+v-no+1a7"
      data-ad-client="ca-pub-8122******"
      data-ad-slot="2872******"></ins>
    <ins v-else 
      class="adsbygoogle"
      style="display:block"
      :data-ad-channel="channel"
      data-ad-client="ca-pub-8122******"
      data-ad-slot="7368*****"
      data-ad-format="auto"
      data-full-width-responsive="true"></ins>
  </component>
</template>

<script>
import Vue from 'vue'
import VueObserveVisibility from 'vue-observe-visibility'
Vue.use(VueObserveVisibility)

export default {
  props: {
    '_class': Array, 
    'tag': {
      type: String,
      default: 'div'
    },
    'type': {
      type: String,
      default: 'display'
    },
    'channel': {
      type: String,
      default: 'nochannel'
    }
  },
  head() {
    if (this.isShow) {
      return {
        script: [
          { hid: 'adsense', src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8122******', async: true, crossorigin: 'anonymous' }
        ]
      }
    }

    return { }
  },  
  data() {
    return {
       isShow: this.$config.ENABLE_ADSENSE,
       isLoaded: false
    }
  },
  methods: {
    visibilityChanged(isVisible, entry) {
      // load when component is shown
      if (isVisible && this.isShow && !this.isLoaded) {
        this.isLoaded = true
        try {
          // this is required for each ad slot (calling this once will only load 1 ad)
          (window.adsbygoogle = window.adsbygoogle || []).push({})
        } catch (error) {
          console.error(error)
        }
      }
    }
  },
  mounted() {
    if (this.isShow) {
      // load after 8s
      setTimeout(() => {
        if (!this.isLoaded) {
          this.isLoaded = true
          try {
            // this is required for each ad slot (calling this once will only load 1 ad)
            (window.adsbygoogle = window.adsbygoogle || []).push({})
          } catch (error) {
            console.error(error)
          }
        }
      }, 8000);
    }
  },
}
</script>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.