How do I change the Javascript src file on client side?

筅森魡賤 提交于 2019-12-13 17:28:31

问题


Within my body tag, I have this:

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

Is it possible to add Javascript or jQuery in the head of the page to change the "key" parameter in the script source. I am trying to do this before the render reaches the above tag.


回答1:


It is not possible to change the src attribute before the render reaches the tag, because modern browsers will download and parse the script as soon as it reaches a script tag (in that particular format).

You can use the defer attribute to hold off execution of the script until after the DOM has completely loaded, but this attribute is only supported in IE 4+ and Firefox 3.5+.




回答2:


why not dynamically create the script tag triggered by onload.

In onload: make the JQuery call, create the src url from the result, append the script tag.




回答3:


I don't know that you could change the key parameter before that script is rendered but you could dynamically write the entire script tag like this:

var script = document.createElement('script');

script.setAttribute('src', 'http://maps.google.com/maps?file=api&amp;v=2.x&amp;key='
                     + param_ssKey + '/');
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);


来源:https://stackoverflow.com/questions/3669536/how-do-i-change-the-javascript-src-file-on-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!