Skip to content

Instantly share code, notes, and snippets.

@clayperez
Created December 19, 2014 07:03
Show Gist options
  • Save clayperez/face9be204e5758be8cf to your computer and use it in GitHub Desktop.
Save clayperez/face9be204e5758be8cf to your computer and use it in GitHub Desktop.
FAST DOC FRAGGING

FAST DOC FRAGGING

A demonstration of faster DOM construction with docfrags. I decided to make it colorful.

A Pen by Carlos Perez on CodePen.

License.

<div id="box1"></div>
"use strict";
var resetButton = document.getElementById("reset");
function launch(){
var allRows = document.createDocumentFragment(),thisRow;
var docBuilder = {
quickEmpty : function(parentNode){
while (parentNode.firstChild) {
parentNode.removeChild(parentNode.firstChild);
}
},
quickFrag : function(properties){
properties.type = properties.type || "div";
var thisFrag = document.createDocumentFragment(),
tag = document.createElement(properties.type);
if(properties.id) {tag.id = properties.id;}
if(properties.class) {tag.className = properties.class;}
if(properties.html) {tag.innerHTML = properties.html;}
if(properties.frag) {tag.appendChild(properties.frag);}
if(properties.cssStyle) {
for(var styleProperty in properties.cssStyle){
tag.style[styleProperty]=properties.cssStyle[styleProperty];
}
}
return thisFrag.appendChild(tag);
},
quickAttach: function(targetID,thisFrag){
document.getElementById(targetID).appendChild(thisFrag);
}
}
docBuilder.quickEmpty(document.getElementById("box1"));
for(var row=1; row <= 1; row++){
thisRow = docBuilder.quickFrag({"class":"row"});
for(var cell=1; cell<=1800; cell++){
var randomColor = Math.floor(Math.random()*16777215).toString(16);
thisRow.appendChild(docBuilder.quickFrag({
"class":"cell",
"cssStyle":{
"backgroundColor":"#"+randomColor
}
}));
}
allRows.appendChild(thisRow);
}
docBuilder.quickAttach("box1",allRows);
setTimeout(launch);
}
launch();
html,body,* {padding:0;margin:0;box-sizing:border-box;}
body {background:rgba(0,0,0,0.8)}
#box1 {display:block;}
#box1 .row {display:block;height:25px;}
#box1 .cell {
display:inline-block;
width:25px;height:25px;
margin:1px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment