AJAX-enabled Infinite Scroll With Template

AJAX-enabled Infinite Scroll With Template
File Size: 8.19 KB
Views Total: 131
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

infiniteScrollWithTemplate.js is a lightweight and easy-to-use jQuery plugin to implement AJAX-enabled Infinite Scrolling in your web app.

The plugin fetches data using AJAX requests and loads more content in your document on page scroll or you click a custom trigger element like Load More button.

Works on both desktop and mobile. Based on the jsrender JavaScript templating engine.

See Also:

How to use it:

1. Load the needed jQuery and jsrender JavaScript libraries in the document.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/cdn/jsrender.min.js"></script>

2. Load the Load InfiniteScrollWithTemplate plugin.

<script src="jquery.infiniteScrollWithTemplate.js"></script>

3. Create a custom template for data rendering.

<script id="my-tmpl" type="text/x-jsrender">
  <p>{{:id}}. {{:title}}</p>
</script>

4. Create a container to which the new content is appended on page scroll.

<div id="result"></div>

5. Initialize the plugin and determine the data source.

$("#result").infiniteTemplate({
  templateSelector: "#my-tmpl",
  dataPath: "data_sources.ajax",
  query: "word=ajax",
});

6. The data should return AJAX response as follows.

{
  "data": [
      {
        "id": 1,
        "title": "Title 1"
      },
      {
        "id": 2,
        "title": "Title 2"
      },
      {
        "id": 3,
        "title": "Title 3"
      },
      // more data here
  ]
}

7. Enable a Load More button to load more content instead of Page Scroll.

<button id="loadmore">Load More</button>
$("#result").infiniteTemplate({
  templateSelector: "#my-tmpl",
  dataPath: "data_sources.ajax",
  query: "word=ajax",
  loadSelector: $('#loadmore'),
});

8. More plugin options with default values.

$("#result").infiniteTemplate({

  // POST, PUT, DELETE
  method: "GET",

  // Merge with json to load
  templateHelpers: null,

  // load on page load
  loadAtStart: true,

  // Load more data when the selector gets clicked
  loadSelector: null,

  // initial page
  initialPage: 1,

  // prevent cache
  preventCache: false,

});

9. Execute a callback function when there is no result.

$("#result").infiniteTemplate({
  templateSelector: "#my-tmpl",
  dataPath: "data_sources.ajax",
  query: "word=ajax",
  zeroCallback: function () {
    alert("zero alert");
  },
});

This awesome jQuery plugin is developed by cable8mm. For more Advanced Usages, please check the demo page or visit the official website.