[1편] jQuery 라이브러리 연동 및 ready() 이해
개발/jquery

[1편] jQuery 라이브러리 연동 및 ready() 이해

반응형

제이쿼리

CDN 방식 연결

<script
  src="https://code.jquery.com/jquery-3.6.0.slim.min.js"
  integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI="
  crossorigin="anonymous"></script>

해당 코드를 <head></head> 태그 사이에 넣습니다.

 

html에서 자바스크립트가 읽히는 순서는 위에서 아래로 순차적으로 작동합니다.

아래 소스를 실행시키면 상단 - 중단 - 하단 순으로 alert() 창이 뜨는것을 볼 수있습니다.

<!DOCTYPE html> 
<html> 
    <head>
      <script 
          src="https://code.jquery.com/jquery-3.6.0.slim.min.js"
          integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI="
          crossorigin="anonymous"
      >
      </script>
      <script type="text/javascript">
         alert('상단')
      </script>
    </head> 
    <body>
    	<h1>hello world!</h1>
        <h2>hello world!</h2>
        <script type="text/javascript">
            alert('중간')
        </script>
        <h3>hello world!</h3>
        <h4>hello world!</h4>
        <script type="text/javascript">
            alert('하단')
        </script>
    </body> 
</html>

하지만 ready() 메소드를 사용하면 스크립트가 위에서 아래로 실행되자만 ready() 로 감싼 부분은 맨 마지막에 실행되게끔 합니다.

<!DOCTYPE html> 
<html> 
    <head>
      <script 
          src="https://code.jquery.com/jquery-3.6.0.slim.min.js"
          integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI="
          crossorigin="anonymous"
      >
      </script>
      <script type="text/javascript">
         alert('상단')
      </script>
    </head> 
    <body>
    	<h1>hello world!</h1>
        <h2>hello world!</h2>
        <script type="text/javascript">
            $(document).ready(function(){
                alert('중간')
            })
        </script>
        <h3>hello world!</h3>
        <h4>hello world!</h4>
        <script type="text/javascript">
            alert('하단')
        </script>
    </body> 
</html>

 

반응형

'개발 > jquery' 카테고리의 다른 글

[2편]jQuery 입력 태그 값 Value GET/SET  (0) 2021.08.05