smooth-javascript

Smooth and fast frontend JSON loading system

Usage no npm install needed!

<script type="module">
  import smoothJavascript from 'https://cdn.skypack.dev/smooth-javascript';
</script>

README

Smooth.JS

npm GitHub forks

Tired of loading feed items directly from your backend? Smooth.js uses super-simple XMLHttpRequests to dynamically and smoothly serve content instead!

Concept

Smooth.JS takes a URL, a container and a template. It queries the URL (which should return a JSON array) and outputs the template into the container for each item in the array (the amount to output at a time is specified in the options).

Smooth.JS is useful, for example, when loading a user's timeline. Instead of loading every single feed item into the page at once (which could be very slow), you can use Smooth to load them systematically and display a 'Load more' button to load the next batch. The button can be made to disappear when the array has been completely exhausted.

Installation

To install Smooth.js, you can use NPM and then link the installed module into your HTML file's head:

npm i smooth-javascript
<!DOCTYPE html>
<html>
  <head>
    <title>My First Smooth Project</title>
    <script src="node_modules/smooth-javascript/dist/smooth.js"></script>
  </head>
</html>

You can also use a CDN (we recommend jsDelivr):

<!DOCTYPE html>
<html>
  <head>
    <title>My First Smooth Project</title>
    <script src="https://cdn.jsdelivr.net/npm/smooth-javascript@0.1.0/dist/smooth.js" integrity="sha256-eps2SNkBVmhkXlcKC9h/gtg2mFjNmOcxcX3IZkodHVo=" crossorigin="anonymous"></script>
  </head>
</html>

Starter

Smooth.JS is a complex and expanding JS library which supports a variety of usage complexities. The following starter file, however, shows the simplest implementation of Smooth. It gets entries from a placeholder API and outputs them into a container 5 at a time, and hides the 'More' button when all items have loaded:

<!DOCTYPE html>
<html>
  <head>
    <title>My First Smooth Project</title>
    <script src="https://cdn.jsdelivr.net/npm/smooth-javascript@0.1.0/dist/smooth.js" integrity="sha256-eps2SNkBVmhkXlcKC9h/gtg2mFjNmOcxcX3IZkodHVo=" crossorigin="anonymous"></script>
  </head>
  <body>
    <div id="container"></div>
    <a href="#!" onclick="more(); return false;" id="more">More...</a>
    <script>
      var smooth = new Smooth("https://jsonplaceholder.typicode.com/posts"); //Initialize Smooth class with specified URL
      smooth.setOptions({ //Set Smooth options
        step:5, //Output 5 at a time
        verb:"GET", //Use GET in XMLHttpRequests
      });
      smooth.setTemplate('<h3>{{title}}</h3><p>{{body}}</p><hr/>'); //Set template for each item. {{key}} is replaced with the specified key from the JSON response.
      smooth.setContainer(document.getElementById("container")); //Set the container to output templates into
      
      function more(){ //Invoked when the 'More' link is clicked
        smooth.more(function(err){ //Load the next batch of items (5 more)
          if(err){
            throw err; //If callback returns an error, throw it
          }
        });
      }
      
      more(); //Load first batch of items on page load.
      
      window.addEventListener('sm_all_rendered',function(e){ //Smooth dispatches the 'sm_all_rendered' event when every item has been rendered
        document.getElementById("more").style.display = "none"; //Hide the link when all have been rendered
      });
    </script>
  </body>
</html>

This page can be found at examples/index.html.

Reference

Smooth()

Intializes Smooth.JS class with specified URL.

Parameters
Parameter Purpose
URL [String] Specifies the JSON API that Smooth should query. Requesting this page should return a JSON array, like the example in the Starter.
Usage
var smooth = new Smooth(url);
Returns

Smooth.JS class object, must be assigned to variable.

.setOptions()

Sets custom options for using Smooth with a specified JSON object.

Parameters
Parameter Purpose
Options [JSON] Specifies custom options in the form of a JSON object. See JSON information below.
###### Options
Field Purpose
------------------ --------------------------------------------------------------------------------------------------------------------------------------------
step [Integer] The amount of items Smooth should load on each call. Defaults to 5.
verb [String] Either "GET" or "POST" - the HTTP verb to use in the query.
useAsync [Boolean] true - XMLHttpRequest should be async; false - it should be sync.
urlParams [String] Parameters to place into the URL. This shouldn't include the preceding ?. These will act as POST parameters if the verb is set to POST
###### Usage
```javascript
var smooth = new Smooth();
smooth.setOptions({
step: 5,
verb: "GET"
});
```
###### Returns
None

.setTemplate()

Sets the template that should output for each item in the specified container.

Parameters
Parameter Purpose
Template [String] A special string of HTML to output for each item. See below for custom values.
###### Template
The template can be simple HTML:
```javascript
smooth.setTemplate("

Hello!

");
```
However, you can also use {{variable}} to output any field from the JSON object per item:
```javascript
smooth.setTemplate("

{{title}}

");
```
You can also use [[javascript]], which will eval() any JS inside it and place the result in the output. For example:
```javascript
smooth.setTemplate("<h1 id=[[Math.floor(Math.random() * 100)]]");
```
The specified JS will be evaluated individually for every single item.
###### Usage
```javascript
var smooth = new Smooth();
smooth.setOptions({
step: 5,
verb: "GET"
});
smooth.setTemplate("

Hello!

");
```
###### Returns
None

.setContainer()

Sets the container to output parsed templates into for each item.

Parameters
Parameter Purpose
Container [Element] A DOM element to output each (parsed) template into per item.
###### Usage
```javascript
var smooth = new Smooth();
smooth.setOptions({
step: 5,
verb: "GET"
});
smooth.setTemplate("

Hello!

");
smooth.setContainer(document.getElementById("myElement"));
```
###### Returns
None

.more()

Loads the next (or first) batch of items, as specified by options (which must be set before this function is called).

Parameters
Parameter Purpose
Callback [Function (error)] Function to execute on completing start of all request or at first error.
###### Usage
```javascript
var smooth = new Smooth();
smooth.setOptions({
step: 5,
verb: "GET"
});
smooth.setTemplate("

Hello!

");
smooth.setContainer(document.getElementById("myElement"));

smooth.more(function(err){ if(err){ console.log(err); } });

#### Event: `sm_object_render`
Dispatched to `window` when a single item has been rendered.
###### Usage
```javascript
window.addEventListener("sm_object_render",function(e){
  console.log("Object rendered");
});

Event: sm_sequence_rendered

Dispatched to window when an instance of .more() has finished outputting items.

Usage
window.addEventListener("sm_sequence_rendered",function(e){
  console.log("Sequence rendered");
});

Event: sm_all_rendered

Dispatched to window when all items have been rendered (the JSON array has been exhausted).

window.addEventListener("sm_all_rendered",function(e){
  console.log("All rendered");
});