There are several types of DOM nodes. There are Document
, Element
, Text
and many more, which also implement the generalized Node
. One of the more interesting, yet until now not so often used ones, is the DocumentFragment
node. It is basically a special container for nodes.
A DocumentFragment
node is treated specially in many DOM algorithms. In this article we will see some of the API methods that are designed for use in conjunction with the DocumentFragment
. We will also see that the concept of node containers is important for other modern web technologies, such as the <template>
element or the whole shadow DOM API. But before we start we should have a quick look at fragment parsing, which is not directly related to the DocumentFragment
.
An HTML5 parser can be used for more than just parsing a complete document. It can also be used for parsing a part of a document, called a fragment. Setting properties such as innerHTML
or outerHTML
will trigger fragment parsing. Fragment parsing works similar to regular parsing with a few exceptions. The biggest difference is the need for a contextual root.
The fragment that is being parsed is likely placed as the child of some element, which may or may not have additional ancestors. This information is crucial to determine the current parsing mode, which depends on the current tree’s hierarchy. Additionally, fragment parsing will not trigger script execution due to security reasons.
We may therefore use code like the following, but we won’t see the additional output. The script execution won’t be triggered.
var foo = document.querySelector('#foo'); foo.innerHTML = '<b>Hallo World!</b><script>alert("Hi.");</script>';
Using fragment parsing is a simple way to reduce DOM operations. Instead of creating, changing and appending nodes, which all involve context switches and therefore DOM operations, we work exclusively in constructing a string, which is then evaluated and handled from the parser. Hence we only have a single, or just a few, DOM operations. The disadvantage of this method is that we require the parser and more work in JavaScript. The key question is: What is more time-consuming? Are the various DOM operations more expensive than all the required JavaScript string manipulations, or is it the other way round?
Clearly this depends on the case. For a particular scenario, Grgur Grisogono did the work to compare the performance using several methods. It also depends highly on the browser, especially how fast the JavaScript engine is. A higher value means more operations and is therefore desired.
Even though browsers are faster these days, the relative behavior is still valid. This should motivate us to search for better solutions and learn more about the DocumentFragment
.
The idea behind the DocumentFragment
node is simple: a container for Node
objects. When a DocumentFragment
is appended, it is expanded to append only the contents of the container, not the container itself. When a deep copy of a DocumentFragment
is requested, its content is cloned as well. The container itself will never be attached to another node, even though it has to have an owner, which is the document
that created the fragment.
Creating a DocumentFragment
works as follows:
var fragment = document.createDocumentFragment();
From this point on, fragment
behaves exactly like any other DOM parent node. We can attach nodes, remove nodes or access existing nodes. The option for running CSS queries using querySelector
and querySelectorAll
is available. Most importantly, as already mentioned, we can clone the node using cloneNode()
.
If document fragments are so great, why not use them for templating? Well, a DocumentFragment
cannot be constructed in plain HTML, as the concept is only exposed via the DOM API. It is therefore only possible to create containers in JavaScript. This reduces the usage benefits a lot. Right now the most popular approach is still text-oriented. We start by placing our template in a pseudo <script>
element. The element is pseudo, because the type
attribute will be set to an invalid mime-type. This way nothing will be executed, but the text content of the element will use different parsing rules.
The image above shows the tokenization states. The parsing rules for script
tags are special, since parsing will take place with a special tokenization state. HTML knows five tokenization states, but the fifth one, Plaintext, is not of great interest for us. The Rawtext state is very similar to Script, which leaves us with three states to explain.
Let’s consider an example. We use three elements that are good representatives for each of the three remaining states. The <div>
element is, as many others, in the parsed characters (PCData) regime. The <textarea>
, uses RCData like, e.g., the <title>
element. Even more like raw characters is the Rawtext state, which could be represented by using a <style>
element. There are subtle differences regarding escaping between the Rawtext and Script state. However, we will treat them as equivalent in the following discussion.
var example = '<br>me & you > them'; var types = ["div", "textarea", "script"]; types.forEach(function (type) { var foo = document.createElement(type); foo.innerHTML = example; console.log(foo.innerHTML); })
Maybe we would expect that the output is the same, but even knowing that there are differences: Who knows what they look like?
<br>me & you > them <br>me & you > them <br>me & you > them
Only the last one matches the input string perfectly. Hence we have a clear winner. So this explains why <script>
elements are so popular for transporting the templating fragments. But here is where the funny part starts. Most templating engines will create a function from the string, which takes a model and spits out a list of generated DOM nodes for the view. Some may already bind the values depending on the model. The important part is the node generation, which is mostly string-oriented, at least during the first iteration.
The W3C recognized the situation and reacted by introducing the <template>
element. The element can be understood as a DocumentFragment
carrier. Since the DocumentFragment
does not participate directly in the DOM tree, it is attached to a node via a property. Using the element is as easy as the following example:
<template> <img src="{src}" alt="{alt}"> <div class="comment">{comment}</div> </template>
In the DOM we won’t see any children of this element. All children have been attached to the contained DocumentFragment
instance, which can be accessed via the content
property.
Let’s get these children:
var fragment = document.querySelector('template').content; var img = fragment.querySelector('img'); var comments = fragment.querySelectorAll('.comment');
The text has been inserted in curly braces to indicate our intention of treating them as placeholders. There is no system of filling them out automatically.
Let’s create a function to return the instantiated nodes for us. We tailor the code for the previous example.
function createNodes (model) { var fragment = document.querySelector('template').content; var instance = fragment.clone(true);//deep cloning! var img = instance.querySelector('img'); img.setAttribute('src', model.src); img.setAttribute('alt', model.alt); var div = instance.querySelector('div'); div.textContent = model.comment; return instance; }
Generalization is possible by iterating over all attributes of elements and child nodes, replacing text that matches a predefined structure in attributes and text nodes. Finally the instantiated nodes can be appended somewhere:
var nodes = createNodes({ src: 'image.png', alt: 'Image', comment: 'Great!' }); document.querySelector('#comments').appendChild(nodes);
There are three important aspects of the <template>
element:
DocumentFragment
accessible via content
.Finally, a document fragment is so useful that it can be even utilized to make small parts of websites re-usable and more flexible.
In recent years the demand for web components has exploded. Many of the front-end frameworks try to mimic a kind of web component structure. It is required, however, to have real DOM support, even though polyfills are certainly possible. The Polymer project is a good example of great polyfills, showcasing what could be done with web components.
What the shadow DOM allows us to do is to append a DocumentFragment
to any Element
. There are three constraints:
DocumentFragment
has to be special—it has to be a ShadowRoot
.Element
can only have one ShadowRoot
, or none of course.ShadowRoot
are separated from the original DOM.These constraints have consequences.
One consequence of attaching a ShadowRoot
to an element is that the element is not rendered any more—instead the content within the shadow DOM is rendered. The content is scoped, however, which means that it may follow its own styling rules. Also the whole event handling process is a little bit different.
As a result, another new concept has been introduced: slots. We can define slots in our shadow DOM, which are filled with nodes from the element, which hosts the ShadowRoot
. It seems obvious that creating custom elements, which carry the shadow DOM, is a good idea. The whole custom elements specification is a reaction to that.
So how can we use the shadow DOM? Let’s do some JavaScript to reveal the API. We start with the following HTML fragment:
<div id="#shadow-dialog"> <span slot="header"> My header title </span> <div slot="content"> <strong>Some very important content</strong> </div> </div>
At this point everything behaves as usual. Here is where our JavaScript skills are demanded:
var context = document.querySelector('#shadow-dialog'); var root = context.attachShadow({ mode: 'open' }); var headerSlot = document.createElement('slot'); headerSlot.name = 'header'; root.appendChild(headerSlot); var contentSlot = document.createElement('slot'); contentSlot.name = 'content'; root.appendChild(contentSlot);
Up to here we have not gained much. We started with some elements, and we are back with them. Effectively the composed DOM tree would look as follows:
<div id="#shadow-dialog"> <slot name="header"> <span slot="header"> My header title </span> </slot> <slot name="content"> <div slot="content"> <strong>Some very important content</strong> </div> </slot> </div>
By default, all nodes of our shadow root are assigned to a default slot, if there is one. A default slot does not have a name
. So what have we gained? We integrated some transparent elements—congratulations! But even more importantly, our original markup does not have to change in order to change the structure, attributes or layout of our composed DOM tree. We only need to change which elements are appended to the shadow root, and that’s it. We have essentially modularized the front-end.
Now some people may think that we had similar techniques already on the server-side. And of course some client-side frameworks also try to aggregate code like this. There are some key differences, however. First, we have the browser’s full support (if implemented). Second, the sandboxing makes rendering with specific rules for that module easy—no clash with existing CSS rules. It is essentially guaranteed that the module works on every page. No more debugging to see where the CSS rules interfere with each other. Finally, we produce much nicer code. It’s easy to generate and cheap to transport, and we can expect even better performance.
The DocumentFragment
is a useful helper that has the ability to reduce the number of DOM operations drastically. It is also an important cornerstone of modern technologies, especially in the web components area. It has already generated two really outstanding technologies: the <template>
element and ShadowRoot
. While the former simplifies templating a lot, giving us a nice performance speedup and an elegant way to transport pre-generated nodes, the latter is the foundation for web components.
Is it really worth knowing about the DocumentFragment
? Probably not yet. If we’re writing a framework or library then it is definitely a must, but most users will be happy that is very likely already used in their favorite front-end library, such as jQuery, Angular, and others. They all use the DocumentFragment
in one or more places to overcome potential performance hits. Is a virtual DOM faster than the real one? Yes, of course, but it may not be as fast without using a DocumentFragment
to aggregate multiple operations.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/Hands-on With ARIA: Accessibility Recipes for Web Apps
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: HTTP
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…