是否有可能像chjQuery网站那样在jQuery中预加载?
我问,因为我有一个Web应用程序,我的第一页有很多脚本需要加载,页面在加载时显示丑陋2-4秒,所以我需要预加载.有人知道插件吗?
有一个简单的加载屏幕,调用包含您的网页的另一个HTML文档:
$(function () {
$.get('real-page.html', function (serverResponse) {
$('#container').fadeOut(350, function () {
$(this).html(serverResponse).fadeIn(350);
});
});
});
Run Code Online (Sandbox Code Playgroud)
这将在document.ready事件触发时请求您的代码,并且当从服务器返回响应时,此代码将淡出"container"元素,将其HTML替换为来自服务器的响应,然后淡入淡出.
如果要加载一堆外部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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
注意:您可以看到所有jqXHR.push()语句,它们将jqXHR对象添加到每个AJAX请求的数组中,这样我们就可以确保每个语句在执行任何更多工作之前已经解决.
另请注意:确保您的服务器在将JS文件发送到浏览器之前压缩它们.如果不这样做,请缩小生产代码.这是一个很好的缩小工具:http://htmlcompressor.com/compressor.html