Search
Duplicate

createDocumentFragment()

생성일
2023/02/11 04:07
태그
JS

createDocumentFragment()

DocumentFragment는 다른 노드를 담는 임시 컨테이너 역할을 하는 특수 목적의 노드이다.
가상의 노드 객체로서, 메모리상에서만 존재하는 비문서 템플릿으로 생각하면 된다.
parentNode 프로퍼티는 항상 null!
하지만 Element처럼, appendChild()와 insertBefore() 등으로 조작할 수 있는 자손 객체를 가질 수 있다.
주로 성능 최적화할 때 사용한다.
예를들면 $table → $tr → $td 이렇게 백개를 하면 일일히 다 메모리를 사용해야 하므로 성능이 떨어질 수 있다.
하지만 $table → $fragment → $tr → $td 이렇게 가상 태그를 만들어서 사용하면 메모리상에만 저장이되서 성능 개선에 도움을 준다.
// $table -> $fragment -> $tr -> $td function startGame() { const $fragment = document.createDocumentFragment(); // 화면 조작할 때 자주 사용, 성능 개선에 도움이 된다 // fragment는 메모리에만 저장된다 // 가상 태그 만들어서 사용 [1, 2, 3, 4].forEach(function() { const rowData = []; data.push(rowData); const $tr = document.createElement('tr'); [1, 2, 3, 4].forEach(() => { rowData.push(0); const $td = document.createElement('td'); $tr.appendChile($td); }); $fragment.appendChild($tr); }); $table.appendChild($fragment); put2ToRandomCell(); draw(); }
JavaScript
복사

화면을 빈번하게 조작할 때는 fragment를 쓰는 습관을 들이자!