Javascript 如何在页面加载后通过 jQuery 动态插入 <script> 标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3857874/
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
How to dynamically insert a <script> tag via jQuery after page load?
提问by Doug
I'm having problems getting this to work. I first tried setting my script tags as strings and then using jquery replaceWith() to add them to the document after page load:
我在让它工作时遇到问题。我首先尝试将我的脚本标签设置为字符串,然后在页面加载后使用 jquery replaceWith() 将它们添加到文档中:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
But I got string literal errors on that var. I then tried encoding the string like:
但是我在那个 var 上遇到了字符串文字错误。然后我尝试对字符串进行编码,如:
var a = '&left;script type="text/javascript">some script here<\/script>';
but sending that to replaceWith()
outputs just that string to the browser.
但将其发送到replaceWith()
仅将该字符串输出到浏览器。
Can someone please let me know how you would go about dynamically adding a <script>
tag into the browser after page load, ideally via jQuery?
有人可以让我知道您将如何<script>
在页面加载后动态添加标签到浏览器中,最好是通过 jQuery?
回答by Rocket Hazmat
You can put the script into a separate file, then use $.getScript
to load and run it.
您可以将脚本放入一个单独的文件中,然后使用$.getScript
它来加载和运行它。
Example:
例子:
$.getScript("test.js", function(){
alert("Running test.js");
});
回答by Bassem
Try the following:
请尝试以下操作:
<script type="text/javascript">
// Use any event to append the code
$(document).ready(function()
{
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://scriptlocation/das.js";
// Use any selector
$("head").append(s);
});
回答by jcoffland
Here's the correct way to do it with modern (2014) JQuery:
这是使用现代(2014)JQuery 执行此操作的正确方法:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.appendTo('head');
})
or if you really want to replace a div you could do:
或者如果你真的想替换一个 div 你可以这样做:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.replaceAll('#someelement');
});
回答by iman
A simpler way is:
更简单的方法是:
$('head').append('<script type="text/javascript" src="your.js"></script>');
You can also use this form to load css.
您也可以使用此表单加载 css。
回答by ddlab
This answer is technically similar or equal to what jcoffland answered. I just added a query to detect if a script is already present or not. I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)
这个答案在技术上类似于或等于 jcoffland 的回答。我刚刚添加了一个查询来检测脚本是否已经存在。我需要这个,因为我在一个有几个模块的 Intranet 网站工作,其中一些是共享脚本或自带脚本,但这些脚本不需要每次都再次加载。我在生产环境中使用这个片段已经一年多了,它就像一个魅力。对自己评论:是的,我知道,询问函数是否存在会更正确... :-)
if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
$('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}
回答by santinobonora
Example:
例子:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
It should work. I tried it; same outcome. But when I used this:
它应该工作。我尝试过这个; 同样的结果。但是当我使用这个时:
var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
html += '<div id="codeSnippet"></div>';
html += '<script type="text/javascript">';
html += 'your script here';
html += '</script>';
}
$('#someElement').replaceWith(a);
This worked for me.
这对我有用。
Edit: I forgot the #someelement
(btw I might want to use #someElement
because of conventions)
编辑:我忘记了#someelement
(顺便说一句,#someElement
由于约定我可能想使用)
The most important thing here is the += so the html is added and not replaced.
这里最重要的是 += 所以 html 被添加而不是被替换。
Leave a comment if it didn't work. I'd like to help you out!
如果它不起作用,请发表评论。我愿意帮你!
回答by Ash
There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:
有一种解决方法听起来更像是一种 hack,我同意这不是最优雅的方法,但 100% 有效:
Say your AJAX response is something like
假设您的 AJAX 响应类似于
<b>some html</b>
<script>alert("and some javscript")
Note that I've skipped the closing tag on purpose.Then in the script that loads the above, do the following:
请注意,我故意跳过了结束标记。然后在加载上述内容的脚本中,执行以下操作:
$.ajax({
url: "path/to/return/the-above-js+html.php",
success: function(newhtml){
newhtml += "<";
newhtml += "/script>";
$("head").append(newhtml);
}
});
Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.
只是不要问我为什么:-) 这是我在绝望的几乎随机试验和失败后得出的结果之一。
I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.
我没有关于它如何工作的完整建议,但有趣的是,如果您将结束标记附加在一行中,它将不起作用。
In times like these, I feel like I've successfully divided by zero.
在这样的时候,我觉得我已经成功地除以零了。
回答by Gagik Sargsyan
Here is a much clearer way — no need for jQuery — which adds a script as the last child of <body>
:
这是一个更清晰的方法——不需要 jQuery——它添加一个脚本作为 的最后一个子项<body>
:
document.body.innerHTML +='<script src="mycdn.js"><\/script>'
But if you want to addand loadscripts use Rocket Hazmat's method.
但是,如果您想添加和加载脚本,请使用Rocket Hazmat 的方法。
回答by Magnar
If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval
. However, JavaScript is such a dynamic language that you really should not have a need for that.
如果您尝试运行一些动态生成的 JavaScript,使用eval
. 然而,JavaScript 是一种动态语言,您真的不需要它。
If the script is static, then Rocket's getScript
-suggestion is the way to go.
如果脚本是静态的,那么 Rocket 的getScript
-suggestion 就是要走的路。