【问题标题】:Lazy load json data from template engine (handlebars)从模板引擎(车把)延迟加载 json 数据
【发布时间】:2017-10-13 20:13:11
【问题描述】:

我正在尝试使用 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/,但我愿意接受任何建议。

感谢您花时间查看,非常感谢您的帮助!

【问题讨论】:

    标签: javascript jquery handlebars.js lazy-loading template-engine


    【解决方案1】:

    问题似乎出在脚本的顺序和时间上。这将是一个竞争条件。您应该在加载模板后立即初始化 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
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2014-01-29
      • 2016-05-18
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      相关资源
      最近更新 更多