본문 바로가기
JavaScript

[JavaScript] CDN을 이용한 jQuery 설치 및 간단한 사용 예제

by happenstance 2021. 8. 10.

🌳 jQuery 설치하기

1. jQuery 파일을 다운받아 script에 경로 지정하기

2. 그리고 script에 jQuery 문법을 작성하기

=> 하지만 이와 같은 방법은 번거롭기 때문에 CDN으로 설치한다.

 

🌳 jQuery 설치하기 - CDN 이용

1. jQuery CDN 홈페이지 접속하기

https://code.jquery.com

 

jQuery CDN

The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libr

code.jquery.com

 

2. jQuery 3.x 버전의 minified(미니버전 - 공백 제거 버전(용량 적음)) 클릭하기

 

 

3. 상단의 script 코드를 복사하여 내가 작성하는 파일에 붙여넣기

 

jQuery 설치 끝!

 

 

4. 그렇다면 어디에 붙여 넣어야 할까?

jQuery 설치 위치는 중요하다.

jQuery 파일을 첨부한 곳에서부터 jQuery 문법을 이용 가능하다.

=> <head> 태그 안에 넣을까?

     단점 : html 파일을 브라우저가 위에서부터 한 줄 씩 해석하는데,

             위의 script 코드 안의 외부 js 파일과 같은 파일을 발견하면 실행을 잠시 멈추고

             파일을 다운받아온다. 브라우저는 파일을 가져올 때가지 기다린다.

             => 로딩이 오래 걸림

=> <body> 태그가 끝나기 전에 넣어주는 것이 이상적이다.

 

 


 

- 자바스크립트의 목적 : HTML 변경

jQuery 문법을 사용하면 HTML 변경을 더 쉽게 할 수 있다.

 

 

 

🌳 jQuery 사용 예제

<!-- 자바스크립트를 조금 더 짧게 쓸 수는 없을까? -->
<!-- JS 코드 양을 줄일 수 있는 방법 => jQuery -->
<!-- addEventListener처럼 긴 코드를 사용하지 않아도 됨 -->
<!-- jQuery: '라이브러리'라고 함 -->
<!-- jQuery로 HTML 변경하기 -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="3_main.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script>
</head>

<body>
    <h4 id="test">안녕하세요</h4>

    <div class="alert-box" id="alert">
        <p id="title">Alert box</p>
        <!-- <button onclick="입력('none')"> X </button> -->
        <!-- 위의 코드를 onclick을 사용하지 않고 작성하기 -->
        <button id="close"> X </button>
    </div>
    <button onclick="알림창열기('아이디를 입력하세요.')">버튼1</button>
    <button onclick="알림창열기('비밀번호를 입력하세요.')">버튼2</button>

    <script>
        /* document.getElementById('test').innerHTML = '???'; */
        /* 위의 코드를 아래와 같이 변경할 수 있음 */
        /* id가 'test'인 것을 찾음 (즉, document.getElementById('test')와 비슷한 의미를 가짐) */
        $('#test').html('안녕'); /* html 대신 text로도 변경 가능(html이 더 큰 의미를 가짐) */
        
        /* jQuery로 HTML을 출력하고 싶을 때 : 괄호 안에 내용 작성 X */
        $('#test').css('color', 'red'); /* .css를 활용하면 글자 색을 바꿀 수도 있음 */
        
        /* jQuery로 HTML의 다른 속성을 변경하고 싶을 때 */
        /* $('css셀렉터').attr(무엇을, 어떻게) */
    </script>
</body>

</html>