javascript jquery 使用脚本更改脚本的 src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8031079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript jquery change src of a script using a script
提问by David19801
I have a javascript script. It has a src element to it. This src is a url, and I would like to change it using javascript, just once to something else, or create it dynamically.
我有一个 javascript 脚本。它有一个 src 元素。这个 src 是一个 url,我想使用 javascript 将它更改为其他内容,或者动态创建它。
What's the best way to create a script element dynamically using javascript/jquery?
使用 javascript/jquery 动态创建脚本元素的最佳方法是什么?
I have:
我有:
<script type="text/javascript" src="http://www.google.com"></script>
I want to change the url above to a different url using javascript/jquery.
我想使用 javascript/jquery 将上面的 url 更改为不同的 url。
回答by Gazler
A pure JavaScript way to inject a script tag (at the bottom of the tag).
一种注入脚本标签的纯 JavaScript 方式(在标签底部)。
document.body.appendChild(document.createElement('script')).src='http://myjs.com/js.js';
回答by arb
A jQuery solution to dynamically inject a JavaScript file
一种动态注入 JavaScript 文件的 jQuery 解决方案
$('<script>').attr({
src: 'www.google.com',
type: 'text/javascript'}).appendTo('body')
This will create a new script tag with a source pointing to www.google.com and append it to the body tag.
这将创建一个新的脚本标签,其源指向 www.google.com 并将其附加到正文标签。
回答by zzzzBov
回答by David says reinstate Monica
I'd suggest using something like this:
我建议使用这样的东西:
var head = document.getElementsByTagName('head')[0];
var newScript = document.createElement('script');
newScript.src = 'http://path.to/script.js';
newScript.type = 'text/javascript';
head.parentNode.appendChild(newScript);