Iframes have their uses, but they are not easy to deal with.
I added some text advertisements to our product this week. The standard technique for including advertising is to use an iframe. This works well for banner ads which come in well-known sizes.
I immediately ran into a problem with text ads in an iframe: there's no easy way to apply CSS to the contents of the iframe. Styles do not cascade through the iframe barrier. Normally, this is what you want, a self-contained unit on the page. It's fine for a banner ad, which requires no styling, but Times Roman text is jarring in a page of Arial.
It's difficult, perhaps outright impossible, to inject styles into an iframe coming from another domain.
Another problem is knowing how big to make the iframe. They don't autosize and the ad text could be one or more lines long.
I needed another way.
Making an Ajax call to fetch just the raw data that I cared about (title, body copy, link) was the obvious answer. A little wad of JSON would be much easier to deal with than trying to style an iframe. Unfortunately, the XMLHTTPRequest object cannot make cross-domain calls. But I read up on JSONP last week, so I knew that I could inject a script tag into my HTML DOM and set the src attribute to the adserver.
jQuery makes this easy: jQuery.getScript injects the script tag and removes it after the script has loaded.
We uploaded a custom template to the adserver:
setAdText({
"adTitle": "%%TITLE%%",
"bodyCopy": "%%BODYCOPY%%",
"clickUrl": "%%CLICKURL%%"
});
I put this call to invoke the adserver's template in my page:
$.getScript(adServerUrl + cache_busting_random_token());
And the setAdText handler in my HTML page looks like this:
function setAdText(data)
{
console.log("setAdText: adTitle=[%s], bodyCopy=[%s], clickUrl=%s."
data.adTitle, data.bodyCopy, data.clickUrl);
// add the ad to the DOM
}
Problem solved.





Comments