Skip to content

Instantly share code, notes, and snippets.

@thejefflarson
Created June 21, 2010 15:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thejefflarson/447011 to your computer and use it in GitHub Desktop.
Save thejefflarson/447011 to your computer and use it in GitHub Desktop.
// Highly experimental async google ads.
propublica.views.googleAds = propublica.Deferrable.extend({
cssClass: "ad",
init : function(){
this._super();
},
render : function(){
// Add google attributes
var accepted = "author,scope,project,type".split(",");
$('meta').each(function(){
var el = $(this);
var name = el.attr('name');
if(_.include(accepted, name)){
_.each(el.attr('content').split(','), function(attr){
if(attr.replace(/\s*/g, "").length > 0) GA_googleAddAttr(name, attr.replace(/[^\w\s]+/g, "").replace(/\s+/g, "_"));
});
}
});
// Setup the google slots
this.el.each(function(){
try{
GA_googleAddSlot("ca-pub-7566226630144794", JSON.parse($(this).attr("data-ad"))["slot"]);
} catch(e){ return; }
});
// Fetch the ads
GA_googleFetchAds();
// We need a count so we can start the queue after we're done
this.length = this.el.length;
var self = this;
// google ads should be the last in the queue because they're amazingly messed up
// here be dragons
propublica.app.writeQueue.add(_.bind(self.adify, self));
},
// We'll use a **document.write** proxy to write each of the ads to the document, it's
// super dicey, but hopefully the function queue will protect the write calls.
adify : function(){
propublica.app.writeQueue.stop();
var _write = document.write;
var _cb = window.GA_googleSetAdContentsBySlotForSync;
var self = this;
window.GA_googleSetAdContentsBySlotForSync = function(garbage){
document.write = function(str){
var el = $(self.query().string + '.' + _.keys(garbage)[0]);
if(/script/.test(str)) {
$('script').eq(0).before(str);
} else {
$(str).appendTo(el);
}
};
_cb(garbage);
// We want to make sure the function queue starts and that document write is restored
// when we've placed the last ad.
self.length--;
if(!self.length) {
document.write = _write;
propublica.app.writeQueue.start(); // We want to ensure that we start the queue up again
}
};
this.el.each(function(){
var el = $(this);
self.insertAd(el);
});
},
// This is called through the asyncQueue so that we can be sure that the writes are
// protected. We're proxying **document.write** in here so it's the danger zone.
insertAd : function(el){
try{
var slot_id = JSON.parse(el.attr("data-ad"))["slot"];
} catch(e){ return; }
el.addClass(slot_id);
document.write = function(str){
$('script').eq(0).before($(str).attr({type:'text/javascript'}));
};
GA_googleFillSlot(slot_id);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment