Tips for dynamically loading fresh Google Adsense code with JavaScript without any user interaction

Recently, Google made a change in their ad code by replacing

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js</script>

with

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890123456" crossorigin="anonymous"</script>

Reference: Google Adsense Announcement

The old Adsense code looked like this:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
     crossorigin="anonymous"></script>
<ins class="adsbygoogle"
     style="display:inline-block;width:350px;height:90px"
     data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
     data-ad-slot="XXXXXXXXXX"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

The new Adsense code now looks like this:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
     crossorigin="anonymous"></script>
<ins class="adsbygoogle"
     style="display:inline-block;width:350px;height:90px"
     data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
     data-ad-slot="XXXXXXXXXX"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

The old JavaScript code used to load the Ad after the page load was:

<script type="text/javascript">
        function downloadJSAtOnload() {
        var element = document.createElement("script");
        element.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
        document.body.appendChild(element);
        }
        if (window.addEventListener)
        window.addEventListener("load", downloadJSAtOnload, false);
        else if (window.attachEvent)
        window.attachEvent("onload", downloadJSAtOnload);
        else window.onload = downloadJSAtOnload;
    </script>

Since

?client=ca-pub-xxxxxx" crossorigin="anonymous"
has been added to the new Ad Code script tag, what would be the updated JavaScript code to load the ads?

Answer №1

Lazy loading is a great technique for optimizing website performance, but defer loading can also be an option, although not always recommended. Here is a sample code for defer loading AdSense:

<script>
function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX";
    element.async = true;
    element.setAttribute('crossorigin', 'anonymous');
    document.body.appendChild(element);
}
if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>

For lazy loading AdSense ads, you can explore Lazy Loading Adsense

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to effectively delete the class from a navigation list item

Looking for some inspiration? Check out the basic visuals for this question here. But let me break it down for you. This snippet shows the HTML & CSS behind a tabbed-carousel, with a condensed version for clarity: <style> #myCarousel-100 . ...

Enhancing performance by implementing cache mechanism for storing search results in a table with multiple filtering options using Vue

In my current project, I am utilizing VueJS. However, the issue I am facing is not necessarily exclusive to this framework - but if there is a vue-specific solution available, that would be my preference. The task at hand involves constructing a table wit ...

Navigating iFrames using Phantomjs Watir

Trying to access a login page using my script: Using PhantomJS and Watir. The issue with the login page is that the login textfields are within an iFrame: <iframe class="hiFrame" data-reactid=".0.0.0.1.0.1.0.0.$frame" src="https://instagram.com/accou ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

Tips on deleting information from an object by utilizing Chrome storage mechanisms

In the chrome storage, I have an object structured as follows: { "planA": { 123: {key: 'some key'} 124: {key: 'some other key'} }, "planB": { 223: {key: 'some key'} 234: { ...

Allowing Users to Easily Copy CSS ::before Content

Text inserted via pseudo-elements like ::before and ::after cannot be selected or copied. Is there a way to change this behavior? span::before { content: "including this text"; } <p> When the text of this paragraph is selected and copied, ...

Using Three.js to Showcase Images within a JSON Data Structure

I am currently utilizing version 71 of the library to showcase an image on each side of a 3D object created in Blender. It doesn't matter if different images are used or if one image is repeated. The object is loaded using a load function post its ins ...

What is the best way to navigate through a complex array in React that includes objects and nested arrays?

I have been working on a JavaScript array that includes subobjects with arrays nested in them. My goal is to iterate through the entire parent object using React. Although I attempted the following approach, unfortunately it did not yield the desired outco ...

The Vuetify data-table header array is having trouble accepting empty child associations

My Vuetify data-table relies on a localAuthority prop from a rails backend. Everything runs smoothly until an empty child association (nested attribute) is passed, specifically 'county': <script> import axios from "axios"; exp ...

Devising a method to display configurable products as related items along with their customizable options in Magento

I am in the process of creating an e-commerce website using Magento for a client. The issue I am facing is that when I include a configurable product as a related item, it displays the product but without a checkbox. From what I have researched, Magento do ...

Ways to retrieve information from a request handler

Working with express, node, and handlebars, I've implemented this piece of code to manage POST requests. When a user hits the "add item" button, it captures their input for a city, fetches the weather data for that city using the Open Weather Map API, ...

Using various hues for segmented lines on ChartJS

I am working with a time line chart type and I want to assign colors to each step between two dots based on the values in my dataset object. In my dataset data array, I have added a third item that will determine the color (if < 30 ==> green / >3 ...

Configuring Angular to use ES6 syntax

Trying to integrate angular google maps with es6 syntax has been a challenge for me. In es5, the code typically looks like this: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key&ap ...

Combine TypeScript files in a specific sequence following compilation

I am hoping to utilize gulp for the following tasks: Compiling TypeScript to JavaScript, which is easily achievable Concatenating JavaScript files in a specific order, proving to be challenging Since I am developing an Angular application, it is crucial ...

Is it possible to create a dynamic zig-zag design with CSS that

I am looking to design a dynamic snake/zigzag layout that consists of square images and circles, starting from the center of the container and descending in a winding fashion. The number of elements is not fixed and is generated based on data received fro ...

disable event listeners on the DOM

I am currently developing a web framework and focusing on integrating XSS prevention measures. I have successfully implemented data escaping for database storage, but now I am faced with the challenge of allowing users to save generated HTML without riskin ...

Ensuring validity with Vuelidate for customizable fields

There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same ...

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

Transforming a collection of Javascript objects into a pure Javascript array

After JSON.stringify-ing my JavaScript object, the output looks like this: [ { "item_id": null, "parent_id": "none", "depth": 0, "left": "1", "right": 4 }, { "item_id": "1", "parent_id": ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...