[5] AJAX - fragment identifier를 이용한 초기 페이지 기능 구현(location, hash)

o:kcalb·2022년 12월 30일
0

Ajax

목록 보기
5/9
post-thumbnail

1. fragment identifier(조각 식별자)

🤔 fetch API에서는 단점이 존재한다.
1. 링크인데 밑줄이 없다. (css가 없는 상태에서)
2. 클릭에 따라 웹페이지의 주소가 변경되지 않는다. (공유할 때 힘들다.)

위 단점들을 해결하기 위한 원시적인 방법이 있다.
(최후에 이 방법을 사용하진 않음.)

💥 방법 💥

만약에 location에 hash가 있을 경우 (hash가 있는 상태로 공유 가능)
fetchPage 함수를 실행하며, location의 hash에서 앞 2글자를 제외한 문자열을 갖고 온다.
따라서, 해당 if문 은 오로지 링크를 통해 접속했을 때를 위함이다.

(만약 주소의 해시(#! 해시뱅)가 있으면
해시의 앞부분(#!)을 삭제하고 ex) fetchPage(‘css’)를 불러온다.)

<ol>
  <li>
    <a href="#!html" onclick="fetchPage('html')">html</a>
  </li>
  <li>
    <a href="#!css" onclick="fetchPage('css')">css</a>
  </li>
  <li>
    <a href="#!javascript" onclick="fetchPage('javascript')">javascript</a>
  </li>
</ol>

<br>

<article>

</article>

<script>
  // 리팩토링 함수화
  function fetchPage(name){
    fetch(name).then(function(response){
      response.text().then(function(text){
      	document.querySelector('article').innerHTML = text;
      });
    });
  }

  // hash
  console.log(location); //주소 정보

  if (location.hash) {
  	console.log(location.hash.substr(2));
  	//substr(N) 문자열에서 일부분만 삭제. (#이 떼진다.)
  	fetchPage(location.hash.substr(2))
  } else {
  	fetchPage('welcome');
  }
</script>
profile
모든 피드백 받습니다 😊

0개의 댓글

관련 채용 정보