有没有可能像teambox网站那样在jQuery中预加载?
我问是因为我有一个web应用程序,我的第一个页面有很多脚本要加载,页面在加载时会出现2-4秒的丑陋,所以我需要一个预加载。有没有人知道一个插件?
发布于 2011-12-08 05:34:27
有一个简单的加载屏幕,它调用包含您的网页的另一个HTML文档:
$(function () {
$.get('real-page.html', function (serverResponse) {
$('#container').fadeOut(350, function () {
$(this).html(serverResponse).fadeIn(350);
});
});
});这将在document.ready事件触发时请求您的代码,并且当响应从服务器返回时,此代码将淡出一个“容器”元素,用来自服务器的响应替换它的超文本标记语言,然后淡入。
如果你想加载一堆外部JS文件,你可以这样做:
$(function () {
var scripts = ['/js/script1.js', '/js/script2.js', '/js/script3.js'],//create an array of scripts to get
len = scripts.length,//cache the length of the scripts array
jqXHR = [],//setup array to store jqXHR objects for AJAX requests
html_str = '';//setup string to store HTML
//request HTML from server and save it to variable for later use
jqXHR.push($.get('real-page.html', function (serverResponse) {
html_str = serverResponse;
}));
//iterate through the scripts array requesting each one
for (var i = 0; i < len; i++) {
jqXHR.push($.getScript(scripts[i]));
}
//when all the jqXHR objects resolve then add the HTML to the DOM
$.when(jqXHR).then(function () {
$('#container').fadeOut(350, function () {
$(this).html(html_str).fadeIn(350);
});
});
});注意:您可以看到所有的jqXHR.push()语句,它们将jqXHR对象添加到每个AJAX请求的数组中,这样我们就可以在做任何进一步的工作之前确保每个请求都得到了解析。
另一个注意事项:在将JS文件发送到浏览器之前,请确保您的服务器正在压缩这些文件。另外,如果您不这样做,请缩减您的生产代码。这是一个很好的小型化工具:http://htmlcompressor.com/compressor.html
https://stackoverflow.com/questions/8422750
复制相似问题