[생활코딩] hash를 알아보자

박망키·2022년 2월 18일
0

생활코딩 - Ajax

목록 보기
3/6

html내에서 특정태그의 위치로 가고자할때 태그의 id를 지정해주고 a링크에 href값으로 주어 a를 누르면 그위치로 간다.
그때에 주소창에 보면 ~~~#아이디 이렇게 나오는데 이게 hash다(페이지내의 북마크 느낌).

<!DOCTYPE html>
<body>
  <a href="#three">#three</a>
  <p>
    Lorem ipsum ..........
  </p>
  <p>
    Lorem ipsum .......
  </p>
  <p id="three">
    123123Lorem ipsum ............
  </p>
  <script>
    if(location.hash){
      console.log(location.hash);
    }
    else{
      console.log("hash없어")
    }
  </script>
</body>
</html>

결과

  • a링크 누르기전
  • a링크 누른후 함수를 재호출 하기위해 새로고침

해쉬를 적을땐 href="#!가려는곳"
관습적으로 #는 북마크이기 때문에 !를붙여서 구분한다 해쉬뱅이라고 한다

결과

초기페이지 설정하기

<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="colors.js"></script>
</head>
<body>
  <h1><a href="#welcome">WEB</a></h1>
  <input id="night_day" type="button" value="night" onclick="
    nightDayHandler(this);
  ">
    <li>
      <a href="#!html" onclick="getText('html')">HTML</a>
    </li>
    <li>
      <a href="#!css" onclick="getText('css')">css</a>
    </li>
    <li>
      <a hret="#!JavaScript" onclick="getText('JavaScript')">JavaScript</a>
    </li>
    
  </ol>
  <article>

  </article>
  <script>
    function getText(page){
      fetch(page).then(function(response) {
          response.text().then(function(text) {
              document.querySelector('article').innerHTML = text
          })
        })
    }
    if(location.hash){
      getText(location.hash.substr(2));
    }
    else{
      getText('welcome')
    }
  </script>
</body>
</html>

결과

  • hash가 없는 첫 로드페이지
  • #!html해쉬이동시

단점

검색엔진 최적화가 안된다. 검색엔진은 웹페이지를 다운로드 받아서 분석해야 하는데, 실제 웹페이지에는 내용이 없고 동적으로 백에서 가져오기때문에,네비게이션을 했을때 내용이 안바뀌므로.
최근에는 pjax를 사용(단점을 보완,진화)

profile
무럭무럭 자라는 망키

0개의 댓글