views:

29

answers:

1

Due to some limitations, I cannot have the script tag for the Google Map API available on page load. I have tried adding the script to the page many different ways, including using jQuery to add a script tag like so:

$('head').append('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"&gt;&lt;/script&gt;');

I have also tried to include it in a more manual way, like so:

var script = document.createElement("script");
script.src = 'http://maps.google.com/maps/api/js?sensor=false';
script.type = "text/javascript";
document.head.appendChild(script);

Both of these examples cause the entire page to become white and blank. Any thoughts on how I can do this?

A: 

If you look at the JavaScript returned by the URL you're trying to load from Google, you'll see it contains a document.write() statement:

http://maps.google.com/maps/api/js?sensor=false

function getScript(src) {
    document.write('<' + 'script src="' + src + '"' +
                   ' type="text/javascript"><' + '/script>');
}

document.write() is a command that's only available during page load. It cannot be called afterwards, or you will experience those results that you mention. Google doesn't want you to load this particular script after the page load.

Dare I say it? Perhaps you need to inject an iframe that points to a page with the google maps code setup so document.write() can work as they designed it.

AndrewDotHay
I see. Hmmmm... I could also change document.write to be a different function before loading it, yes?
JAM
I did it! I did:document.oldWrite = document.write;document.write = function(whatToWrite){ $("body").append(whatToWrite);};document.write = document.oldWrite;
JAM
Now that is crafty!
AndrewDotHay