更新时间:2023-12-05 08:47:10
如果您真的想单独加载它,那正是jQuery的 load
用于.例如,假设您在这些元素上放置了data-page
属性,以告知每个元素应具有的内容:
If you really want to load it separately, that's exactly what jQuery's load
is for. For example, suppose you put a data-page
attribute on those elements telling each of them what content it should have:
<div class="panel" data-page="page1.html">Panel 1</div>
<div class="panel" data-page="page2.html">Panel 2</div>
<div class="panel" data-page="page3.html">Panel 3</div>
<div class="panel" data-page="page4.html">Panel 4</div>
(您没有没有做到这一点,这只是您告诉他们的一种方式.)
(You don't have to do that, it's just one way you might tell them.)
然后按顺序加载它们(如果您确实希望按顺序加载)是相当简单的:
Then loading them sequentially (if you really want it to be sequential) is fairly straight-forward:
// Assumes script is at the bottom of the page, just before </body>
(function() {
var index = 0,
panels = $(".panel");
triggerLoad();
function triggerLoad() {
var panel;
if (index <= panels.length) {
panel = $(panels[index]);
++index;
panel.load(panel.attr("data-page"), triggerLoad);
}
}
})();
这是通过在第一次呈现页面时触发第一个面板的加载,然后使用上一个load
调用的完成处理程序触发随后的每个面板加载来实现的.
That works by triggering the first panel's load when the page is first rendered, and then triggering each of the subsequent panel loads using the completion handler of the previous load
call.
在下面的评论中,您谈到了等待图像等操作.缺少通过Windows获得的主版onload
的body
元素,我们必须检查不完整的图像(HTMLImageElement
具有complete
属性)并挂接其load事件.当没有更多不完整的图像时,我们将加载下一个面板:
In the comments below you talked about waiting for images and such to complete as well. Lacking a body
element for the master onload
that you get with windows, we have to check for incomplete images (HTMLImageElement
has a complete
property) and hook their load event. We load the next panel when there are no more incomplete images:
(function() {
var index = 0,
panels = $(".panel");
nextPanel();
function nextPanel() {
var panel, imgs;
display("Checking for panel #" + index);
panel = panels[index++];
if (panel) {
panel = $(panel);
display("Loading panel");
panel.load(panel.attr("data-page"), panelLoaded);
}
function panelLoaded() {
display("Panel loaded");
imgs = panel.find('img');
imgs.on('load', nextPanelWhenReady);
nextPanelWhenReady();
}
function nextPanelWhenReady() {
var incomplete = imgs.filter(onlyIncomplete);
if (incomplete.length === 0) {
display("No pending images, loading next panel");
imgs.off('load');
nextPanel();
}
else {
display("Images left to load: " + incomplete.length);
}
}
function onlyIncomplete() {
return !this.complete;
}
}
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})();
仅处理图像,但您也应该能够概括视频的概念(我没有处理video
标签,而且我不知道您是在使用它们而不是Flash视频)等等.我也没有处理过.)
That only handles images, but you should be able to generalize the concept for videos as well (I haven't dealt with video
tags, and I don't know that you're using them as opposed to Flash videos, etc. — which I also haven't dealt with).