问题
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&v=2&key=abcdefg" type="text/javascript">
</script>
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/974564/can-i-change-set-the-google-maps-api-key-dynamically-from-javascript