Nach Bildung

“Die arbeitenenden Klassen streben nach Bildung, weil sie sie für ihren Sieg brauchen”

Labour and knowledge is a source of success in every profession. If you have no talent, then—learn, read, study, practice and work as much as you are able. It really helps to succeed.

Wednesday, 27 March 2013

AdSense for responsive websites


As known, Google ASense banners are of fixed size. It is pretty uncomfortable when it concerns responsive websites, yet build in percents (like this very blog). However, certain workaround is possible. Just yesterday I found a fine article that explains in clear language that very technics. The technics works really fine, especially if a layout is built in pixels and controlled by media queries. Extra question, either is how to implement this technics into Blogger.

Well, Blogger has native widget for AdSense and actually no effort is required to add the widget to the blog. However, if we try to achieve its code and customise it we have no that opportunity. Neither in widget ("Edit" in Layout / Wrench Icon in Live blog) nor in xml file. So, my workaround was very simple: I use "Add HTML/Javascript" widget (blank) instead of "AdSense" widget and simply insert the code of my slot which I get from AdSense into there. All the rest is just as described in the above mentioned article.

Here is the full code + brief explanations:

var width = window.innerWidth 
|| document.documentElement.clientWidth 
|| document.body.clientWidth;
google_ad_client = "ca-pub-myId";
if (width > 1440) {
/* Title */
google_ad_slot = "my-slot1";
google_ad_width = 300;
google_ad_height = 250;
} else if ((width < 1440) && (width > 400)) { 
// For screens smaller than 1440px
google_ad_slot = "my-slot2";
google_ad_width = 200;
google_ad_height = 200;
} else { 
// For small screens 
google_ad_slot = "my-slot3";
google_ad_width = 125; 
google_ad_height = 125;

First off you need to create at least three units in AdSense site. Every id is unique so you insert three various ids into code above. Second thing is a variable with width (note, it is a width of a screen, not of a div where the banner is placed). And third thing is to define banner of which size should be shown on various screen widths. In my example above: if a screen is bigger than 1440px the banner shown will be 300px wide and 205px high. If a screen is smaller than 1440px but bigger than 400px the banner will be 200px wide and 200px high. And so on.

However, all these calculations are not precise once the layout is calculated in percents. In this very blog, the sidebar is actually set to 26% relatively to any screen width, so to calculate correctly the exact width of the banner is not totally impossible but will require really hard work.


Post a Comment