npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

smooth-javascript

v0.1.2

Published

Smooth and fast frontend JSON loading system

Downloads

6

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/[email protected]/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/[email protected]/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 | Required | Default | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | | step [Integer] | The amount of items Smooth should load on each call. Defaults to 5. | Yes | None | | verb [String] | Either "GET" or "POST" - the HTTP verb to use in the query. | Yes | None | | useAsync [Boolean] | true - XMLHttpRequest should be async; false - it should be sync. | No | true | | 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 | No | null |

Usage
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:

smooth.setTemplate("<h1>Hello!</h1>");

However, you can also use {{variable}} to output any field from the JSON object per item:

smooth.setTemplate("<h1>{{title}}</h1>");

You can also use [[javascript]], which will eval() any JS inside it and place the result in the output. For example:

smooth.setTemplate("<h1 id=[[Math.floor(Math.random() * 100)]]");

The specified JS will be evaluated individually for every single item.

Usage
var smooth = new Smooth();
smooth.setOptions({
  step: 5,
  verb: "GET"
});
smooth.setTemplate("<h1>Hello!</h1>");
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
var smooth = new Smooth();
smooth.setOptions({
  step: 5,
  verb: "GET"
});
smooth.setTemplate("<h1>Hello!</h1>");
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
var smooth = new Smooth();
smooth.setOptions({
  step: 5,
  verb: "GET"
});
smooth.setTemplate("<h1>Hello!</h1>");
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
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");
});