Created
March 26, 2009 03:41
-
-
Save graysky/85858 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The situation: Need to dynamically load a Javascript file ("ad.js") from | |
// a 3rd party that displays an ad into a certain div. | |
// The ad javascript basically does this (in reality with an iframe): | |
// document.write("<b>Click on the ad!</b>"); | |
// | |
// This is trivial to incorporate in static HTML, but I had a hell of a time | |
// getting it to work when the page was being constructed dynamically (from the | |
// results of fetching JSON using AJAX.) Things that I would have thought | |
// would work resulted in stomping on the *entire* page body with the results | |
// from the ad. (It appeared like the document.write in the ad JS was re-writing the | |
// body of the page?) My original attempt looked something like this (and I also | |
// tried $.getScript() from jQuery): | |
// | |
// var scriptTag = $("<script></script>") | |
// scriptTag.attr({ | |
// type: "text/javascript", | |
// src: "http://foo.com/javascripts/ad.js" | |
// }); | |
// $('#ad_row').append(scriptTag); | |
// | |
// | |
// Assume the static HTML has: "<div id='ad_row'>Sponsored Link</div>" | |
// and jquery is installed. | |
// | |
// To get the ad to show up correctly I ended up doing this, which seems | |
// very hackish but works. I didn't find anything on Google - most examples | |
// show how to dynamically load a JS file, but not one that is doing a doc.write | |
// that modifies the page contents. | |
// | |
function show_ad() { | |
var ad_url = "http://blah.com/javascripts/ad.js"; | |
// Create a script element in the DOM | |
var e = document.createElement("script"); | |
e.src = ad_url; | |
e.type="text/javascript"; | |
document.getElementsByTagName("head")[0].appendChild(e); | |
// Force it to write the contents to the correct div instead | |
// of into the body by temporarily taking over document.write | |
// | |
var original_write = document.write; | |
document.write = function(s) { | |
// Append the contents of the ad to the ad div. | |
$('#ad_row').append(s); | |
document.write = original_write; // restore original write | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment