[英]On-Demand javascript
I'm wondering if you guys can help me to perform on-demand javascript using AJAX? 我想知道你们是否可以帮助我使用AJAX执行按需javascript? If you can help me with a simple example, I would really appreciate it.
如果您能通过一个简单的例子帮助我,我将不胜感激。
my question is: how to get a javascript code from my server and execute it? 我的问题是:如何从服务器中获取JavaScript代码并执行它?
Thanks for the help 谢谢您的帮助
In fact, you don't even need to use AJAX for this. 实际上,您甚至不需要为此使用AJAX。 Simply append a new
<script>
element to your body. 只需在您的身体上添加一个新的
<script>
元素即可。
Plain Old Javascript : 普通的旧Javascript :
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '/scripts/example.js';
document.body.appendChild(newScript);
Here's the same code using jQuery : 这是使用jQuery的相同代码:
// Traditional
$(document.body)
.append('<script type="text/javascript" src="/scripts/example.js" />');
// Using getScript
$.getScript('/scripts/example.js');
Here's the same code using MooTools : 这是使用MooTools的相同代码:
// Traditional
new Element('script', {type: 'text/javascript',
src: '/scripts/example.js'}
).inject(document.body);
// Using Assets (Recommended)
new Asset.javascript('/scripts/example.js');
If you really want to use AJAX (as stated in the question) you can do so too. 如果您确实想使用AJAX(如问题所述),也可以这样做。 First, you download the javascript normally using XMLHttpRequest and when the download is finished you either eval() it or insert it inside a generated tag.
首先,通常使用XMLHttpRequest下载javascript,下载完成后,您可以eval()或将其插入生成的标记中。
function xhr_load(url, callback) {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
callback(xhr.responseText);
}
}
}
xhr.open("GET", url, true);
xhr.send(null);
}
// (1) download using XHR and execute using eval()
xhr_load('mylib.js', function(response) {
eval(response.responseText);
});
// (2) download using XHR and execute as an inline script
xhr_load('mylib.js', function(response) {
var script =
document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.text = response.responseText;
});
Also, Steve Souders has done amazing job in this field and I can highly recommend watching his talk on this video . 此外,史蒂夫·索德斯(Steve Souders)在这一领域做得非常出色,我强烈建议您观看他在这段视频中的讲话。
I made the following function for being able to load JavaScript files programmatically: 我做了以下功能以能够以编程方式加载JavaScript文件:
Usage: 用法:
loadScript('http://site.com/js/libraryXX.js', function () {
alert('libraryXX loaded!');
});
Implementation: 实现方式:
function loadScript(url, callback) {
var head = document.getElementsByTagName("head")[0],
script = document.createElement("script"),
done = false;
script.src = url;
// Attach event handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
callback(); // execute callback function
// Prevent memory leaks in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
I use a callback function argument, that will be executed when the script is loaded properly. 我使用了一个回调函数参数,该参数将在脚本正确加载后执行。
Also notice that the script
element is removed from the head
after it is loaded and I remove the load
and readystatechange
events by setting them to null
, that is made to prevent memory leaks on IE. 还请注意,
script
元素在加载后已从head
移除,我通过将它们设置为null
来移除load
和readystatechange
事件,以防止IE上的内存泄漏。
I use this code to load-on-demand (using jQuery). 我使用此代码按需加载(使用jQuery)。 Its blocking (but i need it) you can make it synchronous using
async:true
它的阻塞(但我需要它)可以使用
async:true
使其同步
(function(script) {
var included_files = new Array();
this.include = function(script) {
var js_base = '/js/';
if (_.indexOf(included_files, script) == -1){
included_files.push(script);
$.ajax({
url: js_base+script.split('.').join('/')+'.js',
type: 'get',
dataType: 'script',
async: false,
global:false,
});
}
};
})();
It uses jQuery and Underscore.js for .indexOf
but you can ommit latter with your own indexOf function. 它使用jQuery的和Underscore.js为
.indexOf
但你可以ommit后者用自己的indexOf功能。
Good luck. 祝好运。
Get the JavaScript code from the server enclosed in tags, append it into DOM and execute a function. 从包含在标签中的服务器获取JavaScript代码,将其附加到DOM中并执行一个函数。 The function name to execute could come with the same request or it can be predefined.
要执行的功能名称可能带有相同的请求,也可以预定义。
What do need this for? 这需要什么? Perhaps if you could elaborate your goals, a more straightforward method could be found.
也许如果您可以详细说明自己的目标,则可以找到一种更直接的方法。
Javascript gets from the web server to the user's browser in a couple of ways: Javascript可通过以下两种方式从Web服务器获取到用户的浏览器:
<script>
tag <script>
标记中的HTML一起嵌入网页中。 <script>
tags can call the code in this separate .js file <script>
标记中的代码可以调用此单独的.js文件中的代码 CMS has shown a solid (looking, haven't tested) library independent method. CMS显示了一种可靠的(外观尚未测试)独立于库的方法。 Here's how you do it in Dojo.
这是在Dojo中的操作方法。
dojo.require("namespace.object");
You may need to specifiy the path to your namespace (ie: root folder) 您可能需要指定名称空间的路径(即:根文件夹)
dojo.registerModulePath("namespace", "../some/folder/path");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.