프론트엔드 첫걸음

createDocumentFragment 본문

개발 공부/Javascript

createDocumentFragment

차정 2023. 2. 4. 22:51
const docFragment = document.createDocumentFragment();

 

비어있는 documentFragment 객체를 만드는 함수

const docFragment = document.createDocumentFragment();
for(let i = 0; this.#slideNumber; i++) {
  const li = document.createElement('li');
  li.dataset.index = i;
  docFragment.appendChild(li);
}
this.wrapperEl.querySelector('ul').appendChild(docFragment);

비어있는 객체에 li를 넣은뒤에 빈객체에 차례로 넣고,  documentFragment객체를 ul안에 넣어서 
동적인 list를 만들 수 있다. 이 방법을 사용하면 for문안에서 매번 appendChild 하는것보다(돔 조작을 1번만 해도 되니까) 속도가 더 빨라진다.

 

 

 

[참고]

https://stackoverflow.com/questions/38260907/do-i-need-to-use-documentfragment-to-insert-ul-list%EF%BB%BFhttps://blog.hao.dev/web-api-appendchild-v-s-createdocumentfragment

 

Web API: appendChild V.S. createDocumentFragment · Hao's learning log

All the JavaScript rendering libraries and frameworks we use, all boils down to the fundamental web APIs at the end of the day. People are so used to work with the high-level React APIs or Vue syntaxes (me included), we forget the raw and interesting layer

blog.hao.dev

 

See the Pen Untitled by JEONG (@cona) on CodePen.