Ajax

리펙토링 - 함수화

appmaster 2021. 3. 12. 16:49

중복되는 소스코드

다음의 함수를 살펴보면 알 수 있는것은, 중복되는 코드가 많다는 부분입니다.

 

 

중복되는 코드는 따로 만들어서 그 함수를 호출해서 쓰는것이 좋습니다.

중복되는 함수 리펙토링

다음과 같이 하면 유지보수도 쉬워지고, 코드양이 줄어들고, 가독성도 높아지게 되었습니다.

 

 

<!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="index.html">WEB</a></h1>
  <input id="night_day" type="button" value="night" onclick="
    nightDayHandler(this);
  ">
  <ol>
    <li><a onclick="fetchPage('html')">HTML</a></li>
    <li><a onclick="fetchPage('css')">CSS</a></li>
    <li><a onclick="fetchPage('javascript')">JavaScript</a></li>
  </ol>
  <!-- <h2>WEB</h2>
  <p>The World Wide Web (abbreviated WWW or the Web) is an information space where documents and other web resources are
    identified by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be accessed via the
    Internet.[1] English scientist Tim Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser
    computer program in 1990 while employed at CERN in Switzerland.[2][3] The Web browser was released outside of CERN
    in 1991, first to other research institutions starting in January 1991 and to the general public on the Internet in
    August 1991.
  </p> -->
  <article>

  </article>

  <script>
    function fetchPage(name){
      fetch(name).then(function(response){
      response.text().then(function(text){
          document.querySelector('article').innerHTML = text;
        })
      });
    }
  </script>
</body>

</html>

'Ajax' 카테고리의 다른 글

fragment identifier를 이용한 초기 페이지 기능 구현  (0) 2021.03.12
Ajax 이용해보기  (0) 2021.03.12
fetch API - response 객체  (0) 2021.03.12
fetch API 기본 사용법  (0) 2021.03.12
Ajax란?  (0) 2021.03.12