• Stars
    star
    185
  • Rank 208,271 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿ“‘ Lightweight dom diffing with plain old html.

Set-DOM Logo
API stability Standard NPM version Build status Test Coverage File size Downloads Gitter Chat Browser Matrix

A lightweight library to update DOM and persist state. IE: React diffing with html instead of JSX (bring your own templating language).

Why

JSX is great but there are so many other nice alternatives. React is great but it's clunky and opinionated.

This is inspired by diffhtml, morphdom and my knowledge from tusk. I set out to create a no nonsense "dom to dom" diffing algorithm that was fast and compact.

Features

  • ~800 bytes min/gzip.
  • Minimal API.
  • Keyed html elements (data-key or id to shuffle around nodes).
  • Use whatever you want to generate html.

Installation

Npm

npm install set-dom

Download

<script type="text/javascript" src="set-dom.js"></script>
<script>
    define(['set-dom'], function (setDOM) {...}); // AMD
    window.setDOM; // Global set-dom if no module system in place.
</script>

Example

const setDOM = require("set-dom");

// We will use handlebars for our example.
const hbs = require("handlebars");
const homePage = hbs.compile(`
    <html>
        <head>
            <title>My App</title>
            <meta name="description" content="Rill Application">
        </head>
        <body>
            <div class="app" data-key="home-page">
                {{title}}
                {{#each frameworks}}
                    <div data-key={{name}}>
                        {{name}} is pretty cool.
                    </div>
                {{/each}}
            </div>
            <script src="/app.js"/>
        </body>
    </html>
`);

// You can replace the entire page with your new html (only updates changed elements).
setDOM(document, homePage({
    title: "Hello World.",
    frameworks: [
        { name: "React" },
        { name: "Angular" },
        { name: "Ember" },
        { name: "Backbone" },
        { name: "Everything" }
    ]
}));

// Or update individual elements.
setDOM(myElement, myHTML);

API

  • setDOM(HTMLEntity, html|HTMLEntity) : Updates existing DOM to new DOM in as few operations as possible.

Advanced Tips

Keys

Just like React (although slightly different) set-dom supports keyed nodes. To help the diffing algorithm reposition your elements be sure to provide a data-key or id attribute on nodes inside a map. This is optional but key for performance when re-ordering/modifying lists.

Another key difference from React is that set-dom simply can't tell when you are rendering an entirely different component. As such it is good practice to use data-key when you know that most of the html will be discarded (like when rendering an entirely different page) to skip the diffing process entirely.

Checksum

Another trick to help set-dom with it's diffing algorithm is to provide a data-checksum attribute. This attribute will only do any diff on an element (and it's children) if the checksum changes allowing you to skip diffing entire trees of the document. Check out hash-sum for a quick and simple checksum that you can use in your templates. Simply hash the state/data for your view and set-dom will only do any changes to the document once the hash has changed.

Ignored

Sometimes it is required to simply escape the whole diffing paradigm and do all of the manual dom work yourself. With set-dom it is easy to include these types of elements in the page using a special data-ignore attribute.

Any elements that have a data-ignore will only be diffed when the data-ignore attribute is removed. The only thing set-dom will do for you in this case is automatically add and remove the element.

Event delegation

Unlike React, set-dom does not provide a way for you to add event listeners to your elements. Fortunately there is a simple approach that enables this that you have probably used before (aka jquery), event delegation. Check out something like component-delegate for a lightweight library that does this for you. Or if you are using Rill checkout @rill/delegate.

Mounting and Dismounting.

Often you need the ability to intercept when a component is inserted or removed from the DOM. Keyed elements (those with data-key or id attributes) will automatically emit custom mount and dismount events when they are inserted and removed from the DOM.

You can use these events to handle setup and teardown of complex components along side event delegation.

Overrides

You can also easily override the attributes used for both keying and ignoring by manually updating the KEY, CHECKSUM and IGNORE properties of set-dom like so.

// Change 'data-key' to 'data-my-key'
setDOM.KEY = 'data-my-key'

// Change 'data-checksum' to 'data-my-checksum'
setDOM.CHECKSUM = 'data-my-checksum'

// Change 'data-ignore' to 'data-my-ignore'
setDOM.IGNORE = 'data-my-ignore'

Benchmarks

Benchmarks are available on the vdom-benchmark website.

Contributions

  • Use npm test to run tests.

Please feel free to create a PR!

More Repositories

1

auto-sni

๐Ÿ” Free, automated HTTPS for NodeJS made easy.
JavaScript
1,181
star
2

local-devices

๐Ÿ”ฎ Find devices connected to the current local network.
JavaScript
140
star
3

vdo

๐Ÿท Minimal JSX compatible html focused templating engine.
JavaScript
82
star
4

tusk

UNMAINTAINED - A slim virtual dom implementation.
JavaScript
50
star
5

receptacle

๐Ÿช Multi purpose in memory lru cache with ttl support.
JavaScript
49
star
6

host-proxy

๐Ÿ™‹ Fast, lightweight and transparent http(s) proxy that supports dynamic hostnames.
JavaScript
16
star
7

toll

๐Ÿ™‹โ€โ™‚๏ธ Simple node hostname proxying and registration for micro-services.
JavaScript
16
star
8

parse-form

๐Ÿ“ƒ Utility to easily parse forms in the browser.
TypeScript
13
star
9

Syntux

Highlight.js optimized for browserify and react.
JavaScript
11
star
10

scroll-behaviour

๐Ÿ’ƒ Scroll Behavior polyfill http://iamdustan.com/smoothscroll for universal use.
JavaScript
9
star
11

require-ensure

๐Ÿค Proper require.ensure polyfill for node that is actually async.
JavaScript
9
star
12

set-page

๐Ÿ’† Framework agnostic, isomorphic <html>, <body and <head> rendering utility.
JavaScript
8
star
13

spawn-server-webpack-plugin

๐Ÿ•ดPlugin for automatically starting a node server from memory after building it with Webpack.
TypeScript
8
star
14

loading-tag

Maybefill for a `<loading>` tag which allows for client reordering of async html.
TypeScript
7
star
15

byte-length

๐Ÿ“ Get the real byte length of a string.
TypeScript
7
star
16

mini-querystring

๐ŸŽป Lightweight universal querystring parser.
TypeScript
6
star
17

mini-url

๐Ÿ“– Lightweight universal url parser.
TypeScript
6
star
18

join-url

๐Ÿ‘ฏโ€โ™‚๏ธ Like `path.join` but for urls.
JavaScript
6
star
19

q-flat

๐Ÿฝ Flatten a nested object using query string syntax.
TypeScript
6
star
20

the

โœ… Structured and testable schemas for JavaScript.
JavaScript
5
star
21

marko-vite-fastify-ssg

Marko example using vite, fastify & ssr-to-html to produce a static site.
Marko
5
star
22

as-html

๐Ÿ“„ HTML templating with es6 quasi literals.
JavaScript
5
star
23

htmljs-to-solid-jsx

This is purely an experiment of efficiently compiling Marko's syntax to solid compatible JSX.
TypeScript
5
star
24

is-local-ip

๐Ÿ‘จโ€๐ŸŒพ Check that a given ip address is private.
JavaScript
4
star
25

submit-form

๐Ÿ’พ Utility to easily submit forms in the browser.
JavaScript
4
star
26

benchmark-cli

๐Ÿ‹๏ธโ€โ™€๏ธ CLI application to benchmark JavaScript files.
JavaScript
4
star
27

mocha-snap

File based snapshotting for Mocha tests.
TypeScript
3
star
28

isbrowser

๐Ÿ•ธ A browserify transform to remove server-side code.
JavaScript
3
star
29

mocha-dom

Run Mocha tests in an isolated JSDOM environment.
TypeScript
2
star
30

a-task

๐Ÿ‘ฅ Easily run multiple parallel tasks with node.
JavaScript
2
star
31

fastify-marko-i18n-example

A basic example using Marko + Fastify with i18n
JavaScript
2
star
32

require-load

๐Ÿ—ฃ Asynchronously require files in node.
JavaScript
2
star
33

marko-vite-express-ssr-only

An example showing how to use Marko + Vite with SSR only.
Marko
2
star
34

q-set

๐Ÿด Set a query string style field on an object.
TypeScript
1
star
35

load-stripe

๐Ÿ’ต Load the promisified stripe api in the browser.
JavaScript
1
star
36

md-vars

๐Ÿ“‰ Parse variables from a markdown file in a clean and simple format.
JavaScript
1
star
37

is-typeof

๐Ÿ”ฌ A tool for better type checking in JavaScript.
TypeScript
1
star
38

vite-issue-resolve-id-repro

JavaScript
1
star
39

webpack-dev-server-issue-infinite-reload

https://github.com/webpack/webpack-dev-server/issues/3803
JavaScript
1
star
40

vite-ssr-optimize-deps-cjs-bug

JavaScript
1
star
41

host-to-port

๐Ÿ“ Converts a hostname into a unique valid port.
JavaScript
1
star
42

side-step

๐Ÿ‘€ Intercept Fetch and XHR requests.
JavaScript
1
star
43

vite-ssr-optimize-deps-internals-bug

Importing node internals that ultimately go into SSR optimized deps throws an error.
JavaScript
1
star
44

get-win

Gets the current window/global object in any runtime.
TypeScript
1
star
45

load-frame

Isomorphic browser testing using JSDOM and iframes.
TypeScript
1
star
46

on-event

๐ŸŽค Simpler in-line event delegation for html templates.
JavaScript
1
star