LEARNING JAVASCRIPT - Trang 300

1

There is a way to prevent jQuery from using

$

if it conflicts with another library; see

jQuery.noConflict

.

jQuery in your project, you can either use the variable

jQuery

or the much shorter

$

.

1

In this text, we’ll use the

$

alias.

Including jQuery

The easiest way to include jQuery is by using a CDN:

<

script

src

=

"//code.jquery.com/jquery-2.1.4.min.js"

></

script

>

jQuery 2.x dropped support for Internet Explorer 6, 7, and 8. If you

need to support those browsers, you will have to use jQuery 1.x.

jQuery 2.x is considerably smaller and simpler because it doesn’t

need to support these aging browsers.

Waiting for the DOM to Load

The way a browser reads, interprets, and renders an HTML file is complicated, and

many an unwary web developer has been caught off-guard by attempting to program‐

matically access DOM elements before the browser has had a chance to load them.
jQuery allows you to put your code in a callback that will only be invoked once the

browser has fully loaded the page and the DOM has been constructed:

$

(

document

).

ready

(

function

() {

// code here is run after all HTML has been

// loaded and the DOM is constructed

});

It is safe to use this technique multiple times, allowing you to place jQuery code in

different places and still have it safely wait for the DOM to load. There is also a short‐

cut version that is equivalent:

$

(

function

() {

// code here is run after all HTML has been

// loaded and the DOM is constructed

});

When using jQuery, putting all of your code in such a block is a ubiquitous practice.

276 | Chapter 19: jQuery

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.