从模板引擎(车把)延迟加载 json 数据

Lazy load json data from template engine (handlebars)

我正在尝试使用 handlebars.js 作为模板引擎延迟加载从 json 文件中获取的内容。

我想在滚动条上延迟加载每个 .projects-list div。

这是我的代码。

HTML:

<div class="projects-list">
    <script id="projects-template" type="text/x-handlebars-template">​
        {{#each this}}
        <h1>{{name}}</h1>
        <img class="lazy" src="{{image.small}}" height="130" alt="{{name}}"/>
        <img class="lazy" data-src="{{image.small}}" height="130" alt="{{name}}"/>
        {{/each}}
    </script>
</div>

JS:

$(function () {

// Get project data from json file.
$.getJSON("projects.json", function (data) {

    // Write the data into our global variable.
    projects = data;

    // Call a function to create HTML for all the products.
    generateAllProjectsHTML(projects);

});

// It fills up the projects list via a handlebars template.
function generateAllProjectsHTML(data) {

    var list = $('.projects-list');

    var theTemplateScript = $("#projects-template").html();

    //Compile the template​
    var theTemplate = Handlebars.compile(theTemplateScript);
    list.append(theTemplate(data));
}

$('.lazy').lazy({
    effect: "fadeIn",
    effectTime: 5000,
    threshold: 0
});

});

JSON:

[
  {
    "id": 1,
    "name": "Example Name 1",
    "image": {
      "small": "assets/images/example1.jpg",
      "large": "assets/images/example2.jpg"
    }
},
  {
    "id": 2,
    "name": "Example Name 2",
    "image": {
      "small": "assets/images/example3.jpg",
      "large": "assets/images/example4.jpg"
    }
  }
]

我正在尝试使用这个插件:http://jquery.eisbehr.de/lazy/ 但我愿意接受任何建议。

感谢您抽空查看,非常感谢任何帮助!

问题似乎出在脚本的顺序和时间上。这将是一个竞争条件。您应该在加载模板后立即初始化 Lazy。这应该可以解决该问题。

您甚至可以压缩脚本。并去掉脚本中的jQuery就绪状态,这里不需要。

所以结果应该是这样的:

$.getJSON("projects.json", function(data) {
    var theTemplateScript = $("#projects-template").html();
    var theTemplate = Handlebars.compile(theTemplateScript);

    $("#projects-list").append(theTemplate(data));

    $(".lazy").lazy({
        effect: "fadeIn",
        effectTime: 5000,
        threshold: 0
    });
});