jquery - 加载html,然后在Jquery中使用Ajax加载图像

标签 jquery ajax performance lazy-loading

基本上我在这里寻找的是性能。

$.post(link,     
  function(data){
         //removes the image that was displayed while loading
         $("#loadingImg").remove();

         //append the new content, into the content div
         //and add a div around the new content in order to lazy load
         $("#content").append('<div id="new-page">' + data + '</div>');
         //lazy load the images inside the new div
         $("#new-page").find("img").lazyload({ 
                 placeholder : "/images/white.png", effect : "fadeIn" });
  });

我想使用jquery插件,lazy load ,延迟加载附加到某些内容的图像。现在我可以看出,使用和不使用该代码的延迟加载行的加载时间完全相同(加载大约 20 个图像)。我现在假设 $("#content").append() 行在附加之前等待所有图像加载。

有什么方法可以将 html 放入页面中,阻止浏览器加载该 html 中的图像,然后在用户滚动时加载它们?

顺便说一句,即使我这样做:

data = '<div id="new-page-' + pageCounter + '">' + data + '</div>';
var newData = $(data);
newData.find("img").lazyload({ placeholder : "/images/white.png", effect : "fadeIn" });
$("#content").append(newData);

加载时间仍然相同...

感谢您的帮助!

最佳答案

Is there any way to put the html in the page, halt the browser from loading the images in that html, and then load them as the user scrolls?

是的,就是:jQuery 路径点: http://imakewebthings.github.com/jquery-waypoints/

工作示例:

http://jsfiddle.net/marcosfromero/BbA9M/

HTML:

<img id="first" src="" width="364" height="126" deferred="http://www.google.com/images/logos/ps_logo2.png" />

<div style="height: 500px; ">Some vertical space. Scroll to the bottom</div>

<img id="second" src="" width="364" height="126" deferred="http://www.google.com/images/logos/ps_logo2.png" />

我在此 HTML 代码中发现的唯一缺点是 deferred 属性不是标准的。

jQuery:

$('img').waypoint(function(event, direction) {
    // set the image src attribute from the deferred one, which has the real URL
    this.src = this.getAttribute('deferred');
}, {
    triggerOnce: true, // load the image just once
    offset: function() {
        // calculate where the event should be fired
        // in this case, when the whole image is visible
        return $.waypoints('viewportHeight') - $(this).height();
        // if you want to load the image when the top of it is visible change it for
        // return $.waypoints('viewportHeight');
    }
})

关于jquery - 加载html,然后在Jquery中使用Ajax加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6165643/

相关文章:

javascript - jqPlot 饼图无法正确渲染

javascript - 使用事件克隆 HTML 元素

performance - gatling 注入(inject)用户 vs jmeter 线程组

c - 将 float 写入数组需要太多时间

python - 计算pyspark中两个数据帧的行之间的距离

jquery - SSRS 报告的跨源问题

javascript - 构建一个简单的 WYSIWYG 编辑器

javascript - 在加载中传递变量

ajax - 有没有比在 SharePoint WebParts 中使用 Ajax 更新面板更好的方法?

javascript - 如何正确地将数据从 jQuery 和 Ajax 附加到 HTML?