[英]How to dynamically insert a <script> tag via jQuery after page load?
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 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? 有人可以让我知道您如何在页面加载后(最好是通过jQuery)将
<script>
标记动态添加到浏览器中吗?
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");
});
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);
});
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');
});
A simpler way is: 一个更简单的方法是:
$('head').append('<script type="text/javascript" src="your.js"></script>');
You can also use this form to load css. 您也可以使用此表单加载CSS。
This answer is technically similar or equal to what jcoffland answered. 从技术上讲,该答案与jcoffland的答案相似或相等。 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.
我之所以需要它,是因为我在一个Intranet网站上工作,其中包含两个模块,其中一些模块共享脚本或自带脚本,但是这些脚本不需要每次都重新加载。 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... :-)
对自己说:是的,我知道,问一个函数是否存在会更正确... :-)
if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
$('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}
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%: 有一种解决方法听起来更像是一种破解,我同意这不是最优雅的方法,但可以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. 在这样的时代,我觉得自己已经成功地除以零。
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!
我想帮你!
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 add and load scripts use Rocket Hazmat's method . 但是,如果要添加和加载脚本,请使用Rocket Hazmat的方法 。
If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval
. 如果您尝试运行一些动态生成的JavaScript,那么使用
eval
会更好一些。 However, JavaScript is such a dynamic language that you really should not have a need for that. 但是,JavaScript是一种动态语言,因此您实际上不需要它。
If the script is static, then Rocket's getScript
-suggestion is the way to go. 如果脚本是静态的,那么应该使用Rocket的
getScript
-uggesttion。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.