Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of pushing empty objects into the adsbygoogle array in Adsense tags?

This is the explanation from their site:

A call to adsbygoogle.push(), which instructs us to fill in the first unfilled slot.

But what is the adsbygoogle array used for in the javascript code?

Here is a sample ad tag (see the javascript line at the end):

<ins class="adsbygoogle"
 style="display:inline-block;width:300px;height:250px"
 data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
 data-ad-slot="yyyyyyyyyy"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
like image 627
ramiwi Avatar asked Jun 01 '14 20:06

ramiwi


1 Answers

The script which actually loads AdSense ads, adsbygoogle.js, is loaded asynchronously (i.e. via a <script async> tag). The call to adsbygoogle.push() is a way for the page to tell the script that there is an ad slot to be filled, using code that can be executed either before or after that async-loaded script has executed.

If adsbygoogle.js has not yet loaded, then adsbygoogle.push({}) makes the adsbygoogle array one element longer, which effectively increments the count of how many ad slots are sitting around waiting for adsbygoogle.js to pay attention to them. When adsbygoogle.js loads, it iterates through that queue, processing one ad slot for each queue entry.

Now the clever bit: Once adsbygoogle.js loads, it replaces adsbygoogle.push with a function that causes it to immediately process the new slot. This means adsbygoogle.js doesn't need to poll the DOM for the addition of new slots needing processing. (On modern browsers you could do this with a DOM Mutation Observer, but adsbygoogle predates this.)

This has mostly explained why you do a push() for each slot. As for why you push an empty object, the answer by @JustcallmeDrago gives a good hint: The object you're pushing can contain some other configuration information about the slot, but the empty object {} is a nice short default, and means "fill the first unfilled slot, using the configuration data given by its tag in the DOM."

like image 182
Michael Kleber Avatar answered Sep 22 '22 18:09

Michael Kleber