• Stars
    star
    1,156
  • Rank 38,841 (Top 0.8 %)
  • Language
    HTML
  • License
    ISC License
  • Created over 3 years ago
  • Updated 12 months ago

Reviews

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

Repository Details

A triple-linked lists based DOM implementation.

πŸ”— linkedom

Downloads Build Status Coverage Status

Social Media Photo by JJ Ying on Unsplash

This is not a crawler!

LinkeDOM is a triple-linked list based DOM-like namespace, for DOM-less environments, with the following goals:

  • avoid maximum callstack/recursion or crashes, even under heaviest conditions.
  • guarantee linear performance from small to big documents.
  • be close to the current DOM standard, but not too close.
import {DOMParser, parseHTML} from 'linkedom';

// Standard way: text/html, text/xml, image/svg+xml, etc...
// const document = (new DOMParser).parseFromString(html, 'text/html');

// Simplified way for HTML
const {
  // note, these are *not* globals
  window, document, customElements,
  HTMLElement,
  Event, CustomEvent
  // other exports ..
} = parseHTML(`
  <!doctype html>
  <html lang="en">
    <head>
      <title>Hello SSR</title>
    </head>
    <body>
      <form>
        <input name="user">
        <button>
          Submit
        </button>
      </form>
    </body>
  </html>
`);

// builtin extends compatible too πŸ‘
customElements.define('custom-element', class extends HTMLElement {
  connectedCallback() {
    console.log('it works πŸ₯³');
  }
});

document.body.appendChild(
  document.createElement('custom-element')
);

document.toString();
// the SSR ready document

document.querySelectorAll('form, input[name], button');
// the NodeList of elements
// CSS Selector via CSSselect

What's New

  • in v0.11 a new linkedom/worker export has been added. This works with deno, Web, and Service Workers, and it's not strictly coupled with NodeJS. Please note, this export does not include canvas module, and the performance is retrieved from the globalThis context.

Serializing as JSON

LinkeDOM uses a blazing fast JSDON serializer, and nodes, as well as whole documents, can be retrieved back via parseJSON(value).

// any node can be serialized
const array = document.toJSON();

// somewhere else ...
import {parseJSON} from 'linkedom';

const document = parseJSON(array);

Please note that Custom Elements won't be upgraded, unless the resulting nodes are imported via document.importNode(nodeOrFragment, true).

Alternatively, JSDON.fromJSON(array, document) is able to initialize right away Custom Elements associated with the passed document.

Simulating JSDOM Bootstrap

This module is based on DOMParser API, hence it creates a new document each time new DOMParser().parseFromString(...) is invoked.

As there's no global pollution whatsoever, to retrieve classes and features associated to the document returned by parseFromString, you need to access its defaultView property, which is a special proxy that lets you get pseudo-global-but-not-global properties and classes.

Alternatively, you can use the parseHTML utility which returns a pseudo window object with all the public references you need.

// facade to a generic JSDOM bootstrap
import {parseHTML} from 'linkedom';
function JSDOM(html) { return parseHTML(html); }

// now you can do the same as you would with JSDOM
const {document, window} = new JSDOM('<h1>Hello LinkeDOM πŸ‘‹</h1>');

Data Structure

The triple-linked list data structure is explained below in How does it work?, the Deep Dive, and the presentation on Speakeasy JS.

F.A.Q.

Why "not too close"?

LinkeDOM has zero intention to:

  • implement all things JSDOM already implemented. If you need a library which goal is to be 100% standard compliant, please use JSDOM because LinkeDOM doesn't want to be neirly as bloated nor as slow as JSDOM is
  • implement features not interesting for Server Side Rendering. If you need to pretend your NodeJS, Worker, or any other environment, is a browser, please use JSDOM
  • other points listed, or not, in the followung F.A.Q.s: this project will always prefer the minimal/fast approach over 100% compliant behavior. Again, if you are looking for 100% compliant behavior and you are not willing to have any compromise in the DOM, this is not the project you are looking for

That's it, the rule of thumb is: do I want to be able to render anything, and as fast as possible, in a DOM-less env? LinkeDOM is great!

Do I need a 100% spec compliant env that simulate a browser? I rather use cypress or JSDOM then, as LinkeDOM is not meant to be a replacement for neither projects.

Are live collections supported?

The TL;DR answer is no. Live collections are considered legacy, are slower, have side effects, and it's not intention of LinkeDOM to support these, including:

  • getElementsByTagName does not update when nodes are added or removed
  • getElementsByClassName does not update when nodes are added or removed
  • childNodes, if trapped once, does not update when nodes are added or removed
  • children, if trapped once, does not update when nodes are added or removed
  • attributes, if trapped once, does not update when attributes are added or removed
  • document.all, if trapped once, does not update when attributes are added or removed

If any code you are dealing with does something like this:

const {children} = element;
while (children.length)
  target.appendChild(children[0]);

it will cause an infinite loop, as the children reference won't side-effect when nodes are moved.

You can solve this in various ways though:

// the modern approach (suggested)
target.append(...element.children);

// the check for firstElement/Child approach (good enough)
while (element.firstChild)
  target.appendChild(element.firstChild);

// the convert to array approach (slow but OK)
const list = [].slice.call(element.children);
while (list.length)
  target.appendChild(list.shift());

// the zero trap approach (inefficient)
while (element.childNodes.length)
  target.appendChild(element.childNodes[0]);
Are childNodes and children always same?

Nope, these are discovered each time, so when heavy usage of these lists is needed, but no mutation is meant, just trap these once and use these like a frozen array.

function eachChildNode({childNodes}, callback) {
  for (const child of childNodes) {
    callback(child);
    if (child.nodeType === child.ELEMENT_NODE)
      eachChildNode(child, callback);
  }
}

eachChildNode(document, console.log);

How does it work?

All nodes are linked on both sides, and all elements consist of 2 nodes, also linked in between.

Attributes are always at the beginning of an element, while zero or more extra nodes can be found before the end.

A fragment is a special element without boundaries, or parent node.

Node:             ← node β†’
Attr<Node>:       ← attr β†’          ↑ ownerElement?
Text<Node>:       ← text β†’          ↑ parentNode?
Comment<Node>:    ← comment β†’       ↑ parentNode?
Element<Node>:    ← start ↔ end β†’   ↑ parentNode?

Fragment<Element>:  start ↔ end

Element example:

        parentNode? (as shortcut for a linked list of previous nodes)
            ↑
            β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚                                            ↓
  node? ← start β†’ attr* β†’ text* β†’ comment* β†’ element* β†’ end β†’ node?
            ↑                                            β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜


Fragment example:

            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚                                            ↓
          start β†’ attr* β†’ text* β†’ comment* β†’ element* β†’ end
            ↑                                            β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

If this is not clear, feel free to read more in the deep dive page.

Why is this better?

Moving N nodes from a container, being it either an Element or a Fragment, requires the following steps:

  • update the first left link of the moved segment
  • update the last right link of the moved segment
  • connect the left side, if any, of the moved node at the beginning of the segment, with the right side, if any, of the node at the end of such segment
  • update the parentNode of the segment to either null, or the new parentNode

As result, there are no array operations, and no memory operations, and everything is kept in sync by updating a few properties, so that removing 3714 sparse <div> elements in a 12M document, as example, takes as little as 3ms, while appending a whole fragment takes close to 0ms.

Try npm run benchmark:html to see it yourself.

This structure also allows programs to avoid issues such as "Maximum call stack size exceeded" (basicHTML), or "JavaScript heap out of memory" crashes (JSDOM), thanks to its reduced usage of memory and zero stacks involved, hence scaling better from small to very big documents.

Are childNodes and children always computed?

As everything is a while(...) loop away, by default this module does not cache anything, specially because caching requires state invalidation for each container, returned queries, and so on. However, you can import linkedom/cached instead, as long as you understand its constraints.

Parsing VS Node Types

This module parses, and works, only with the following nodeType:

  • ELEMENT_NODE
  • ATTRIBUTE_NODE
  • TEXT_NODE
  • COMMENT_NODE
  • DOCUMENT_NODE
  • DOCUMENT_FRAGMENT_NODE
  • DOCUMENT_TYPE_NODE

Everything else, at least for the time being, is considered YAGNI, and it won't likely ever land in this project, as there's no goal to replicate deprecated features of this aged Web.

Cached VS Not Cached

This module exports both linkedom and linkedom/cached, which are basically the exact same thing, except the cached version outperforms linkedom in these scenarios:

  • the document, or any of its elements, are rarely changed, as opposite of frequently mutated or manipulated
  • the use-case needs many repeated CSS selectors, over a sporadically mutated "tree"
  • the generic DOM mutation time is not a concern (each, removal or change requires a whole document cache invalidation)
  • the RAM is not a concern (all cached results are held into NodeList arrays until changes happen)

On the other hand, the basic, non-cached, module, grants the following:

  • minimal amount of RAM needed, given any task to perform, as nothing is ever retained on RAM
  • linear fast performance for any every-time-new structure, such as those created via importNode or cloneNode (i.e. template literals based libraries)
  • much faster DOM manipulation, without side effect caused by cache invalidation

Benchmarks

To run the benchmark locally, please follow these commands:

git clone https://github.com/WebReflection/linkedom.git

cd linkedom/test
npm i

cd ..
npm i

npm run benchmark

More Repositories

1

hyperHTML

A Fast & Light Virtual DOM Alternative
HTML
3,028
star
2

document-register-element

A stand-alone working lightweight version of the W3C Custom Elements specification
JavaScript
1,131
star
3

dom4

Modern DOM functionalities for every browser
JavaScript
929
star
4

flatted

A fast and minimal circular JSON parser.
JavaScript
893
star
5

url-search-params

Simple polyfill for URLSearchParams standard
JavaScript
765
star
6

uhtml

A micro HTML/SVG render
JavaScript
707
star
7

lighterhtml

The hyperHTML strength & experience without its complexity πŸŽ‰
JavaScript
702
star
8

JSONH

Homogeneous Collection Compressor
JavaScript
618
star
9

circular-json

JSON does not handle circular references. Now it does
JavaScript
599
star
10

viperHTML

Isomorphic hyperHTML
JavaScript
318
star
11

heresy

React-like Custom Elements via V1 API builtin extends.
JavaScript
271
star
12

es6-collections

Map, WeakMap, and Set fast/simple shim for Harmony collections
JavaScript
253
star
13

neverland

React like Hooks for lighterhtml
JavaScript
241
star
14

wicked-elements

Components for the DOM as you've never seen before
JavaScript
235
star
15

eddy

Event Driven JS
JavaScript
211
star
16

dblite

sqlite for node.js without gyp problems
JavaScript
209
star
17

domdiff

Diffing the DOM without virtual DOM
JavaScript
197
star
18

hyperHTML-Element

An extensible class to define hyperHTML based Custom Elements.
JavaScript
195
star
19

benja

Bootable Electron Node JS Application
194
star
20

uce

Β΅html based Custom Elements
JavaScript
183
star
21

usignal

A blend of @preact/signals-core and solid-js basic reactivity API
JavaScript
176
star
22

highlighted-code

A textarea builtin extend to automatically provide code highlights based on one of the languages available via highlight.js
HTML
172
star
23

restyle

JavaScript
167
star
24

testardo

a browser and OS agnostic web driver for mobile and desktop
JavaScript
166
star
25

sqlite-worker

A simple, and persistent, SQLite database for Web and Workers.
JavaScript
159
star
26

augmentor

Extensible, general purpose, React like hooks for the masses.
JavaScript
135
star
27

uhooks

micro hooks: a minimalistic client/server hooks' implementation
JavaScript
127
star
28

polpetta

Polpetta, any folder is served spiced
JavaScript
125
star
29

basicHTML

A NodeJS based, standard oriented, HTML implementation.
JavaScript
123
star
30

udomdiff

An essential diffing algorithm for Β΅html.
JavaScript
117
star
31

pocket.io

A minimalistic version of socket.io that weights about 1K instead of 60K.
JavaScript
112
star
32

caller-of

The tiniest yet most powerful JS utility ever :D
HTML
102
star
33

uland

A Β΅html take at neverland
JavaScript
101
star
34

uce-template

A Vue 3 inspired Custom Elements toolless alternative.
JavaScript
100
star
35

json.hpack

JSON Homogeneous Collections Packer
C#
95
star
36

html-escaper

A module to escape/unescape common problematic entities done the right way.
JavaScript
95
star
37

wru

essential unit test framework
JavaScript
95
star
38

udomsay

A stricter, signals driven, ESX based library
JavaScript
95
star
39

db

JavaScript
94
star
40

import.js

A dynamic import() polyfill
JavaScript
93
star
41

regular-elements

Custom Elements made available for any node, and through CSS selectors
JavaScript
91
star
42

proxy-pants

Secured and reliable Proxy based utilities for more or less common tasks.
JavaScript
90
star
43

ucompress

A micro, all-in-one, compressor for common Web files.
JavaScript
90
star
44

archibold.io

archibold.io
Shell
85
star
45

jsgtk

A simplified approach to GJS for Node.JS and JavaScript developers.
JavaScript
85
star
46

heresy-ssr

πŸ”₯ heresy πŸ”₯ Server Side Rendering
JavaScript
84
star
47

hypersimple

The easiest way to use hyperHTML
JavaScript
83
star
48

asbundle

A minimalistic JS bundler
JavaScript
77
star
49

introspected

Introspection for serializable arrays and JSON friendly objects.
HTML
77
star
50

node-gtk

GNOME Gtk+ bindings for NodeJS
C++
74
star
51

i18n-utils

The i18n tag function utilitities
JavaScript
73
star
52

viper-news

viperHTML version of the Hacker News app.
JavaScript
72
star
53

ucdn

A Β΅compress based CDN utility, compatible with both Express and native http module
JavaScript
67
star
54

electroff

A cross browser, electron-less helper, for IoT projects and standalone applications.
JavaScript
64
star
55

builtin-elements

A zero friction custom elements like primitive.
JavaScript
62
star
56

nonchalance

The easiest way to augment DOM builtin elements.
JavaScript
61
star
57

universal-mixin

A mixin usable for both generic objects and decorators.
JavaScript
59
star
58

attachshadow

An iframe based Shadow DOM poorlyfill
JavaScript
59
star
59

ucontent

An SSR HTML content generator.
JavaScript
58
star
60

dom-augmentor

Same as augmentor but with DOM oriented useEffect handling via dropEffect.
JavaScript
56
star
61

ascjs

ES2015 to CommonJS import/export transformer
JavaScript
55
star
62

geo2city

Basic offline reverse geocode
JavaScript
53
star
63

vanilla-elements

A Minimalistic Custom Elements Helper.
JavaScript
51
star
64

wrist

Minimalistic utility for generic one/two ways data bindings.
HTML
51
star
65

screenfit

A cross platform, cross WebView, solution to fit 100% any Web page.
HTML
50
star
66

html-parsed-element

A base custom element class with a reliable `parsedCallback` method.
HTML
50
star
67

sqlite-tag

Template literal tag based sqlite3 queries.
JavaScript
49
star
68

jsdon

A DOM serializer based on LinkeDOM idea
HTML
48
star
69

echomd

A terminal oriented MD like syntax
JavaScript
48
star
70

dom-class

A lightweight, cross browser, simplification of WebComponents.
JavaScript
46
star
71

cloner

Cloning ES5+ objects in a shallow or deep way
JavaScript
46
star
72

css-proxied-vars

The easiest way to set, read, or update, CSS variables per each element.
JavaScript
46
star
73

event-target

The EventTarget Class Polyfill.
HTML
46
star
74

hn

Isomorphic Hacker News
JavaScript
45
star
75

proxied-worker

A tiny utility to asynchronously drive a namespace exposed through a Worker.
JavaScript
45
star
76

Database

Web SQL Storage Made Easy
JavaScript
44
star
77

promise

Abortable and Resolvable Promises.
JavaScript
43
star
78

poorlyfills

Simplified, partial, and poor ES6 collections polyfills, targeting IE9+ and older mobile browsers.
HTML
43
star
79

babel-plugin-transform-builtin-classes

A fix for the infamous Babel #4480 bug.
JavaScript
43
star
80

redefine

lightweight utility for smart object properties definition
JavaScript
42
star
81

bidi-sse

Bidirectional Server-sent Events
JavaScript
42
star
82

nativeHTML

coming soon
JavaScript
42
star
83

domtagger

The hyperHTML's template literal parser
JavaScript
41
star
84

hooked-elements

wickedElements πŸ§™ with render hooks
JavaScript
41
star
85

classtrophobic

Breaking JS Class Constrains
HTML
41
star
86

a-route

Express like routing as Custom Element or standalone
JavaScript
40
star
87

header-snippets

A collection of snippets to put in your header.
HTML
40
star
88

life-diary

your albums, your journey, your data
JavaScript
40
star
89

static.email

The easiest way to send emails on the Web
JavaScript
39
star
90

lazytag

Lazy loading Custom Elements and their styles without even thinking about it.
JavaScript
38
star
91

es-class

ECMAScript 3 to 6 compatible Class definition
JavaScript
38
star
92

tiny-cdn

A tiny static files serving handler
JavaScript
37
star
93

broadcast

Notification channel for the past, the present, and the future.
JavaScript
37
star
94

p-cool

Pretty Cool Elements
JavaScript
36
star
95

monthly

A simplified way to show a calendar month in any console.
HTML
36
star
96

jsx2tag

Enable JSX for Template Literal Tags based projects.
JavaScript
36
star
97

consolemd

Bringing echomd to console.
JavaScript
36
star
98

common-js

CommonJS + module.import() for any Browser
JavaScript
35
star
99

qsa-observer

handle elements lifecycle through CSS selectors
JavaScript
35
star
100

create-viperhtml-app

A basic viperHTML + hyperHTML setup
JavaScript
35
star