Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

이미지 미리보기 (createObjectURL vs FileReader) #66

Open
SeonHyungJo opened this issue May 7, 2020 · 0 comments
Open

이미지 미리보기 (createObjectURL vs FileReader) #66

SeonHyungJo opened this issue May 7, 2020 · 0 comments
Labels
📖 HTML HTML도 삽질이 가능합니다. 💌 JavaScript 공부를 해도해도 어려운 JavaScript :shipit: Tip 내가 사용해보니 좋은 팁 👍 type:AWOT AWOT(a waste of time) == 삽질

Comments

@SeonHyungJo
Copy link
Owner

SeonHyungJo commented May 7, 2020

웹에서 많이 사용되는 기능으로 이미지 미리보기가 있다.

이미지 미리보기를 구현하는 방법은 크게 2가지로 나눌 수 있다.

URL.createObjectURL, URL.revokeObjectURL

inputElement.addEventListener('change', (e) => {
  imgElement.src = URL.createObjectURL(e.target.files[0]);
});

URL.revokeObjectURL(imgElement.src)

FileReader.readAsDataURL

function previewFile() {
  const preview = document.querySelector('img');
  const file = document.querySelector('input[type=file]').files[0];
  const reader = new FileReader();

  reader.addEventListener("load", function () {
    preview.src = reader.result;
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}

비교한 글 살펴보기

1) time

  • createObjectURL is synchronously executed (immediately)
  • FileReader.readAsDataURL is asynchronously executed (after some time)

2) memory usage

  • createObjectURL returns url with hash, and store object in memory until document triggers unload event (e.g. document close) or execute revokeObjectURL
  • FileReader.readAsDataURL returns base64 that contains many characters, and use more memory than blob url, but removes from memory when you don't use it (by garbage collector)

3) support

createObjectURL from IE 10 and all modern browsers
FileReader.readAsDataURL from IE 10 and all modern browsers

결론적으로 BLOB 방식의 createObjectURL가 더욱 빠르며 많은 이미지를 보여주어야하는 경우 메모리 해제를 해주어야 한다.

Reference

@SeonHyungJo SeonHyungJo added 💌 JavaScript 공부를 해도해도 어려운 JavaScript 👍 type:AWOT AWOT(a waste of time) == 삽질 📖 HTML HTML도 삽질이 가능합니다. :shipit: Tip 내가 사용해보니 좋은 팁 labels May 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
📖 HTML HTML도 삽질이 가능합니다. 💌 JavaScript 공부를 해도해도 어려운 JavaScript :shipit: Tip 내가 사용해보니 좋은 팁 👍 type:AWOT AWOT(a waste of time) == 삽질
Projects
None yet
Development

No branches or pull requests

1 participant