views:

639

answers:

2

I'm faced with a problem with a small web application I'm developping: My HTML-source will be integrated into the HTML source on another site. I'm using a Google Map in my code, so I have to pass a API-Key for loading the Google Maps-script on the current domain.

The problem: My code will be integrated on two different domains, requiring two different API-Keys. I have those two keys and can identify the valid one by JavaScript (With the help of document.location.host), but how can I manage to dynamically load the script with the correct key?

For reference: The key is passed as parameter in the script loading url:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=abcdefg" type="text/javascript">
</script>
+3  A: 

Use

var script = document.createElement("script");
script.setAttribute("src",whatever);
document.getElementsByTagName("head")[0].appendChild(script);

Replace whatever with the script source you want to use

Jonathan Fingland
Almost, except it needs to be document.getElementsByTagName("head")[0] instead of document.head
Matthew Flaschen
Answering trom an iphone. Was a little hard to check. Thanks
Jonathan Fingland
Ah, thanks, that should have been more or less obvious. (And for the selector: Well, jQuery is kinda convenient for that...)
christian studer
+1  A: 

I just blogged a would-be solution to this problem. Take a look and let me know what you think. It's a context processor that dynamically loads the key based on the domain in the request.