Как подключать библиотеку jquery все способы подключения примеры

link About the Code

jQuery is provided under the MIT license.

The code is hosted and developed in the jQuery GitHub repository. If you’ve spotted some areas of code that could be improved, please feel free to discuss it on the Developing jQuery Core Forum. If you’d like to participate in developing jQuery, peruse our contributor site for more information.

To find and download plugins developed by jQuery contributors, please visit the Plugins site. Plugin authors are responsible for maintenance of their plugins. Feedback on plugins should be directed to the plugin author, not the jQuery team.

Build from Git

Note: To just use the latest work-in-progress version of jQuery, please try the jQuery Pre-Release Build described above.

All source code is kept under Git revision control, which you can browse online. The repository’s README has more information on building and testing your own jQuery, as well as instructions on creating a custom build that excludes some APIs to reduce file size.

If you have access to Git, you can connect to the repository here:

1

You can also check out and build a specific version of jQuery from GitHub:

1

2

The README file for a specific version will have instructions for building that version, as the process has changed over time.

Как скачать jQuery

Для загрузки нам доступны 2 версии: полная и slim. Отличается slim от полной только тем, что в ней отсутствует часть модулей, а именно ajax и effects. Если функции входящие в эти модули нужны, то тогда следует выбрать полную версию. В противном случае – slim.

Кроме этого, каждая из них доступна нам как в сжатом (с суффиксом ) так и в несжатом виде.

Несжатый вариант библиотеки рекомендуется использовать только во время разработки проекта или его отладки. Кроме этого, его ещё используют для изучения исходного кода jQuery. В нём можно посмотреть устройство как всей библиотеки, так и определённой функции.

На продакшене лучше применять сжатый вариант jQuery (с расширением ). Он меньше весит, и, следовательно, быстрее загружается

А это очень важно для производительности сайта

Уменьшение объема JavaScript кода библиотеки jQuery осуществляется за счёт минимизации. Минимизация – это процесс, который заключается в удалении из исходного кода всего лишнего (комментариев, незначащих пробелов, переносов строк, символов табуляции) и замене имен функций и переменных на более короткие.

Кроме этого, существуют разные ветки jQuery: 1.x, 2.x и 3.x.

jQuery 1.x следует использовать если нужна поддержка IE 6 – 8.

jQuery 2.x построено на том же API, что 1.x. Но имеет меньший размер и более высокую производительность. Это было достигнуто благодаря тому, что из неё был удалён устаревший код, необходимый для поддержки IE 6 – 8. Таким образом 2.x можно использовать только в том случае, если вам не нужна поддержка этих старых браузеров.

jQuery 3.x – последняя ветка (3.5.1 – последняя версия). В большинстве случаев рекомендуется выбирать её, если конечно вам не нужна поддержка IE 6 – 8. В отличие от предыдущих веток она имеет множество улучшений (поддержку промисов, работу с анимацией через и др.) и исправлений. Кроме этого, она доступна как в полном формате, так и .

После того как вы определись какой вариант библиотеки вам нужен, его необходимо загрузить.

Для скачивания jQuery с официального сайта нажмите правой кнопкой мыши на нужную ссылку и выберите пункт «Сохранить ссылку как…».

После скачивания, можно заметить, что jQuery представляет обычный файл с расширением . Далее его нужно загрузить на сервер.

Legacy versions

1.3.2

ZIP file

If you want to host the files yourself you can download a zip of all the files:

Zip File: jquery.mobile-1.3.2.zip (JavaScript, CSS, and images)

jQuery CDN

JavaScript:

  • Uncompressed: jquery.mobile-1.3.2.js (useful for debugging)
  • Minified and Gzipped: jquery.mobile-1.3.2.min.js (full library, ready to deploy)

CSS:

  • Uncompressed with Default theme: jquery.mobile-1.3.2.css (useful for debugging)
  • Minified and Gzipped with Default theme: jquery.mobile-1.3.2.min.css (full library, ready to deploy)
  • Uncompressed structure without a theme: jquery.mobile-1.3.2.css (useful for theme development)
  • Minified and Gzipped structure without a theme: jquery.mobile-1.3.2.min.css (to be used with custom theme, ready to deploy)

Copy-and-Paste snippet for jQuery CDN hosted files:

1

2

3

Microsoft CDN

Microsoft CDN – jQuery Mobile

1.2.1

ZIP file

If you want to host the files yourself you can download a zip of all the files:

Zip File: jquery.mobile-1.2.1.zip (JavaScript, CSS, and images)

jQuery CDN

JavaScript:

  • Uncompressed: jquery.mobile-1.2.1.js (useful for debugging)
  • Minified and Gzipped: jquery.mobile-1.2.1.min.js (full library, ready to deploy)

CSS:

  • Uncompressed with Default theme: jquery.mobile-1.2.1.css (useful for debugging)
  • Minified and Gzipped with Default theme: jquery.mobile-1.2.1.min.css (full library, ready to deploy)
  • Uncompressed structure without a theme: jquery.mobile-1.2.1.css (useful for theme development)
  • Minified and Gzipped structure without a theme: jquery.mobile-1.2.1.min.css (to be used with custom theme, ready to deploy)

Copy-and-Paste snippet for jQuery CDN hosted files:

1

2

3

Microsoft CDN

Microsoft CDN – jQuery Mobile

1.1.2

ZIP file

If you want to host the files yourself you can download a zip of all the files:

Zip File: jquery.mobile-1.1.2.zip (JavaScript, CSS, and images)

jQuery CDN

JavaScript:

  • Uncompressed: jquery.mobile-1.1.2.js (useful for debugging)
  • Minified and Gzipped: jquery.mobile-1.1.2.min.js (full library, ready to deploy)

CSS:

  • Uncompressed with Default theme: jquery.mobile-1.1.2.css (useful for debugging)
  • Minified and Gzipped with Default theme: jquery.mobile-1.1.2.min.css (full library, ready to deploy)
  • Uncompressed structure without a theme: jquery.mobile-1.1.2.css (useful for theme development)
  • Minified and Gzipped structure without a theme: jquery.mobile-1.1.2.min.css (to be used with custom theme, ready to deploy)

Copy-and-Paste snippet for jQuery CDN hosted files:

1

2

3

Microsoft CDN

Microsoft CDN – jQuery Mobile

1.0.1

ZIP file

If you want to host the files yourself you can download a zip of all the files:

Zip File: jquery.mobile-1.0.1.zip (JavaScript, CSS, and images)

jQuery CDN

JavaScript:

  • Uncompressed: jquery.mobile-1.0.1.js (useful for debugging)
  • Minified and Gzipped: jquery.mobile-1.0.1.min.js (full library, ready to deploy)

CSS:

  • Uncompressed with Default theme: jquery.mobile-1.0.1.css (useful for debugging)
  • Minified and Gzipped with Default theme: jquery.mobile-1.0.1.min.css (full library, ready to deploy)
  • Uncompressed structure without a theme: jquery.mobile-1.0.1.css (useful for theme development)
  • Minified and Gzipped structure without a theme: jquery.mobile-1.0.1.min.css (to be used with custom theme, ready to deploy)

Copy-and-Paste snippet for jQuery CDN hosted files:

1

2

3

Microsoft CDN

Microsoft CDN – jQuery Mobile

Обращение к элементам в jQuery

Для того чтобы писать код на jQuery, вам понадобится использовать знак $, который является псевдонимом (или сокращением) для идентификатора на jQuery. Например, чтобы выбрать все и добавить css-свойство с помощью jQuery, а также поменять класс при клике на этом блоке, необходимо написать такой код:

Простой скрипт на jQuery

<style>
.jq-test { padding: 10px; background: #90c4f8; }
</style>

<div class=»jq-test»>
<h5>Test Block 1</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio necessitatibus commodi
dolorem natus qui ut suscipit, inventore expedita explicabo, ipsa.</p>
</div>
<div class=»jq-test»>
<h5>Test Block 2</h5>
<p>Facilis veniam praesentium modi possimus repudiandae eaque error eum provident similique
debitis eligendi, laudantium incidunt earum sed ea dicta reprehenderit.</p>
</div>
<div class=»jq-test»>
<h5>Test Block 3</h5>
<p>Ratione possimus ullam dolor fugiat facilis! Eum iusto architecto laudantium ex molestiae commodi,
sed earum nesciunt ut saepe deleniti ea.</p>
</div>
<div class=»jq-test»>
<h5>Test Block 4</h5>
<p>Quibusdam, tempore sapiente distinctio laboriosam explicabo totam deleniti, aliquam consectetur,
ullam dolore non laudantium doloribus. Aperiam alias accusantium iusto quas.</p>
</div>

<script>
$(document).ready(function(){
$(‘.jq-test’).css(‘border-bottom’, ‘5px double #cde’);
$(‘.jq-test’).click(function(){
$(this).toggleClass(«jq-test»);
});
});
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

<style>

.jq-test {padding10px;background#90c4f8;}

</style>
 

<div class=»jq-test»>

<h5>Test Block1<h5>

<p>Lorem ipsum dolor sit amet,consectetur adipisicing elit.Distinctio necessitatibus commodi

dolorem natus qui ut suscipit,inventore expedita explicabo,ipsa.<p>

<div>

<div class=»jq-test»>

<h5>Test Block2<h5>

<p>Facilis veniam praesentium modi possimus repudiandae eaque error eum provident similique

debitis eligendi,laudantium incidunt earum sed ea dicta reprehenderit.<p>

<div>

<div class=»jq-test»>

<h5>Test Block3<h5>

<p>Ratione possimus ullam dolor fugiat facilis!Eum iusto architecto laudantium ex molestiae commodi,

sed earum nesciunt ut saepe deleniti ea.<p>

<div>

<div class=»jq-test»>

<h5>Test Block4<h5>

<p>Quibusdam,tempore sapiente distinctio laboriosam explicabo totam deleniti,aliquam consectetur,

ullam dolore non laudantium doloribus.Aperiam alias accusantium iusto quas.<p>

<div>

 
<script>

$(document).ready(function(){

$(‘.jq-test’).css(‘border-bottom’,’5px double #cde’);

$(‘.jq-test’).click(function(){

$(this).toggleClass(«jq-test»);

});

});

</script>

Код несложный, он добавляет рамку внизу блока. Клик на голубом блоке удаляет/добавляет класс «jq-test» к нему с помощью метода jQuery .

Test Block 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio necessitatibus commodi dolorem natus qui ut suscipit, inventore expedita explicabo, ipsa.

Test Block 2

Facilis veniam praesentium modi possimus repudiandae eaque error eum provident similique debitis eligendi, laudantium incidunt earum sed ea dicta reprehenderit.

Test Block 3

Ratione possimus ullam dolor fugiat facilis! Eum iusto architecto laudantium ex molestiae commodi, sed earum nesciunt ut saepe deleniti ea.

Test Block 4

Quibusdam, tempore sapiente distinctio laboriosam explicabo totam deleniti, aliquam consectetur, ullam dolore non laudantium doloribus. Aperiam alias accusantium iusto quas.

Просмотров:
1 012

jQuery Core — All 3.x Versions

  • jQuery Core 3.6.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.5.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.5.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.4.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.4.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.3.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.3.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.2.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.2.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.1.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.1.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.0.0 — uncompressed, minified, slim, slim minified

Установка версии библиотеки jQuery UI, предназначенной для разработки

Загрузочный архив jQuery UI содержит все файлы, необходимые для использования библиотеки как в процессе разработки, так и в производственной среде. Для работы с примерами вам понадобятся файлы, которые содержат несжатый исходный код и предназначены для использования в процессе разработки. В случае возникновении каких-либо проблем вы сможете легко изучить код для ознакомления с внутренним устройством библиотеки jQuery UI, что окажет неоценимую помощь при отладке сценариев.

Вы должны скопировать в папку с файлами примеров следующие файлы и папки:

  • development-bundle\ui\jquery-ui.custom.js;

  • development-bundle\themes\sunny\jquery-ui.css;

  • папка development-bundle\themes\sunny\images.

Содержащиеся в папках ui и themes файлы JavaScript и CSS используются отдельными компонентами и средствами, входящих в состав библиотеки. У вас не будет необходимости обращаться к ним, но они могут пригодиться в том случае, если вы захотите работать с ограниченным набором средств библиотеки jQuery UI.

Имена JavaScript- и CSS-файлов включают номер версии загруженного выпуска библиотеки. В моем случае это версия 1.10.3. Библиотека jQuery UI активно разрабатывается, и вы можете загрузить более позднюю версию, чем 1.10.3.

Подключение библиотеки jQuery UI к HTML-документу

Все, что вам теперь остается сделать — это включить библиотеку jQuery UI в свой HTML-документ. Это можно сделать, добавив в документ элементы script и link, содержащие ссылки на файлы JavaScript и CSS, которые вы загрузили, как показано в примере ниже:

Ссылаться непосредственно на папку images необязательно. Коль скоро папка images и CSS-файл находятся на своих местах, jQuery UI сможет самостоятельно найти все необходимые ресурсы.

Библиотека jQuery UI зависит от библиотеки jQuery. Для того чтобы использовать jQuery UI в документе, ее следует предварительно подключить к нему. Библиотека jQuery UI не относится к числу автономно используемых библиотек.

Показанный в примере выше документ содержит простой тест, позволяющий проверить правильность подключения библиотеки jQuery UI. В случае нормального открытия страницы вы должны увидеть кнопку, похожую на ту, которая показана на рисунке. Не обращайте пока внимания на вызов метода button() в элементе script. О том, для чего он предназначен и как работает, вы узнаете в следующей статье.

В случае неправильного указания пути к любой из двух библиотек вы увидите вместо этого простую ссылку.

jQuery UI 1.8

uncompressedminified

Themes

baseblack-tieblitzercupertinodark-hivedot-luveggplantexcite-bikeflickhot-sneakshumanityle-frogmint-chocovercastpepper-grinderredmondsmoothnesssouth-streetstartsunnyswanky-pursetrontasticui-darknessui-lightnessvader

Previous Releases

  • jQuery UI 1.8.23 — uncompressed, minified, theme
  • jQuery UI 1.8.22 — uncompressed, minified, theme
  • jQuery UI 1.8.21 — uncompressed, minified, theme
  • jQuery UI 1.8.20 — uncompressed, minified, theme
  • jQuery UI 1.8.19 — uncompressed, minified, theme
  • jQuery UI 1.8.18 — uncompressed, minified, theme
  • jQuery UI 1.8.17 — uncompressed, minified, theme
  • jQuery UI 1.8.16 — uncompressed, minified, theme
  • jQuery UI 1.8.15 — uncompressed, minified, theme
  • jQuery UI 1.8.14 — uncompressed, minified, theme
  • jQuery UI 1.8.13 — uncompressed, minified, theme
  • jQuery UI 1.8.12 — uncompressed, minified, theme
  • jQuery UI 1.8.11 — uncompressed, minified, theme
  • jQuery UI 1.8.10 — uncompressed, minified, theme
  • jQuery UI 1.8.9 — uncompressed, minified, theme
  • jQuery UI 1.8.8 — uncompressed, minified, theme
  • jQuery UI 1.8.7 — uncompressed, minified, theme
  • jQuery UI 1.8.6 — uncompressed, minified, theme
  • jQuery UI 1.8.5 — uncompressed, minified, theme
  • jQuery UI 1.8.4 — uncompressed, minified, theme
  • jQuery UI 1.8.3 — uncompressed, minified, theme
  • jQuery UI 1.8.2 — uncompressed, minified, theme
  • jQuery UI 1.8.1 — uncompressed, minified, theme
  • jQuery UI 1.8.0 — uncompressed, minified, theme

Minor vulnerability fix: Object.prototype pollution

jQuery 3.4.0 includes a fix for some unintended behavior when using . If an unsanitized source object contained an enumerable property, it could extend the native Object.prototype. This fix is included in jQuery 3.4.0, but patch diffs exist to patch previous jQuery versions.

Example

Note that while jQuery does its best to protect users from security vulnerabilities, jQuery is a DOM manipulation library that will generally do what you tell it to do. In this case, the behavior was likely unexpected, so will no longer write any properties named . But guards such as this one are not replacements for good security practices such as user input sanitization.

Получение библиотеки jQuery UI

Процесс загрузки библиотеки jQuery UI отличается несколько большей сложностью по сравнению с другими библиотеками JavaScript, но результат будет стоить затраченных усилий. Библиотека jQuery UI охватывает пять областей функциональности, и вам предоставляется возможность самостоятельно сконфигурировать загрузочный архив, включив в него лишь необходимые компоненты. В этой части вы познакомитесь со всеми возможностями библиотеки jQuery UI, но при работе с реальными веб-приложениями можно исключать ненужные компоненты для уменьшения размера библиотеки, загружаемой браузерами.

Выбор темы оформления

Прежде чем приступить к созданию собственной библиотеки jQuery UI, вы должны выбрать тему оформления. Библиотека jQuery UI предлагает богатейшие возможности и способы выбора конфигураций, благодаря чему можно с легкостью изменить внешний вид любого используемого средства. В действительности число доступных возможностей выбора настолько велико, что иногда это поистине ошеломляет.

На сайте jQuery UI можно воспользоваться услугами специального приложения — настройщика тем (Themeroller), но кроме того существует целая галерея предопределенных тем, полностью готовых к использованию, из которых можно выбрать ту, которая вас больше всего устраивает, и тем самым облегчить себе жизнь.

Начните с посещения сайта jqueryui.com и щелкните на кнопке Themes. В результате откроется страница ThemeRoller, отображающая виджеты jQuery UI и расположенную слева от них панель настроек, с помощью которой можно установить параметры темы оформления, как показано на рисунке:

Если у вас уже используется определенный визуальный стиль, которого вы должны придерживаться, и вы хотите, чтобы визуальный интерфейс средств JQuery UI согласовывался с остальной частью сайта или приложения, то вкладка Roll Your Own (которая выбирается по умолчанию) — это как раз то, что нужно. Можно изменить любой аспект оформления с помощью набора стилей CSS, который используется библиотекой jQuery UI.

Чтобы получить одну из готовых тем, следует перейти на вкладку Gallery. На момент написания этих строк галерея включала 24 темы, охватывающие широкий спектр вариантов цветового оформления — от приглушенных и нежных тонов до ярких и вызывающих. При выполнении щелчков на темах галереи внешний вид виджетов, отображаемых на остальной части страницы, будет соответствующим образом обновляться, позволяя вам оценить, как может выглядеть приложение:

Используемая для jQuery UI стандартная тема носит название UI lightness, но эта тема недостаточно контрастна, и поэтому я буду использовать тему Sunny, которая выглядит немного лучше. Единственное, что от вас сейчас требуется — это запомнить название темы, которая вас устраивает.

Создание настраиваемого загрузочного архива библиотеки jQuery UI

Выбрав для себя определенную тему оформления, можете приступить к созданию собственного варианта загрузки библиотеки jQuery UI. Щелкните на кнопке Download в верхней части страницы для перехода на страницу Download Builder. Вы увидите список компонентов jQuery UI, разбитых на четыре функциональные группы: UI Core, Interactions, Widgets и Effects.

Выбирая лишь те возможности, которые действительно нужны вашему проекту, вы уменьшите размер набора файлов, который должны будут загружать браузеры. Сама по себе эта идея неплохая, но я придерживаюсь другого подхода. С моей точки зрения, гораздо лучше сэкономить часть полосы пропускания своего канала связи и переложить задачу доставки jQuery UI в браузеры на одну из сетей распространения содержимого, о чем будет говориться далее.

Для выполнения примеров вам понадобятся все компоненты, поэтому проследите за тем, чтобы были установлены все флажки.

Между некоторыми компонентами, фигурирующими в списке, существуют зависимости, но в процессе создания своего варианта библиотеки можете об этом не думать. Если вы выбираете какой-либо компонент, то одновременно с ним загрузятся все компоненты, от которых он зависит.

Следующий шаг заключается в выборе темы. Это делается с помощью раскрывающегося списка, который располагается снизу на странице, как показано на рисунке:

У вас также есть возможность выбрать конкретную версию библиотеки jQuery UI, которая должна быть включена в загрузочный архив. Вам потребуется загрузить стабильную (Stable) версию, которая работает со всеми версиями библиотеки jQuery, начиная с версии 1.3.2.

После выделения всех компонентов и выбора темы и стабильной версии загрузите созданный вами пользовательский вариант загрузочного архива библиотеки jQuery UI, щелкнув на кнопке Download.

Manipulation

  • #13232: In 2.0beta1, using html() function on a tbody selector yields insertion of new tbody
  • #13233: Unexpected behavior when iterating over and manipulating detached nodes in jquery 1.9
  • #13282: QtWebKit — TypeError: ‘’ is not a valid argument for ‘Function.prototype.apply’ (evaluating ‘elem.nodeType’)
  • #13596: .replaceWith should always remove the context set
  • #13721: remove(“:nth-child(1)”) works differently than filter(“:nth-child(1)”).remove()
  • #13722: .replaceWith argument handling is inconsistent with other manipulation methods
  • #13779: .remove() changed in beta3 – now remove nodes in reverse doc order

Плюс: простой доступ к странице

В чистом JavaScript обра­тить­ся к объ­ек­ту на стра­ни­це мож­но одним из способов:

document.getElementById(«myElement»)
document.getElementsByTagName(«td»)
document.getElementsByClassName(«myClass»)

и еще несколь­ко подобных

В jQuery то же самое дела­ет одна пре­крас­ная коман­да. Заод­но она же сов­ме­ща­ет в себе кучу дру­гих функ­ций. Фак­ти­че­ски она гово­рит jQuery: «Возь­ми ЭТО и сде­лай с ним что-то»:

$(«myElement»)

Поэто­му какие-то про­стые мани­пу­ля­ции с объ­ек­та­ми на стра­ни­це выгля­дят эле­гант­нее имен­но с jQuery. Это не зна­чит, что их нель­зя делать с про­стым JavaScript — мож­но. Но это не так красиво.

Пример манипуляции с объектами

Пред­ставь­те, что у нас есть стра­ни­ца, на кото­рой есть важ­ные плаш­ки. Такие же, как на этой, и у всех задан класс “SomeClass”. И в зави­си­мо­сти от вре­ме­ни суток, бра­у­зе­ра или настро­е­ния про­грам­ми­ста сайт дол­жен эти плаш­ки скры­вать, добав­лять новые или как-то их менять. Вот, что мож­но, к при­ме­ру, с ними делать:

var $elem = $(«.SomeClass») //Выбираем элементы.

$elem.remove(); //Удаляем их.

добав­лять новые:

$elem.prepend($someOtherElem);

встав­лять ещё одни перед ними:

$elem.before($someOtherElem);

заме­нять их на что-то другое:

$elem.replaceWith($someOtherElem);

и про­сто плав­но пока­зы­вать на экране:

$elem.fadeIn();

How 2.0 Changed

Here are some highlights of the changes that jQuery 2.0 brings:

No more support for IE 6/7/8: Remember that this can also affect IE9 and even IE10 if they are used in their “Compatibility View” modes that emulate older versions. To prevent these newer IE versions from slipping back into prehistoric modes, we suggest you always use an X-UA-Compatible tag or HTTP header. If you can use the HTTP header it is slightly better for performance because it avoids a potential browser parser restart.

Reduced size: The final 2.0.0 file is 12 percent smaller than the 1.9.1 file, thanks to the elimination of patches that were only needed for IE 6, 7, and 8. We had hoped to remove even more code and increase performance, but older Android/WebKit 2.x browsers are now the weakest link. We’re carefully watching Android 2.x market share to determine when we can cross it off the support list, and don’t expect it to take very long.

Custom builds for even smaller files: This feature has been greatly refined and extended since its debut in jQuery 1.8. You can now exclude combinations of 12 different modules to create a custom version that is even smaller. A new minimal selector engine, basically a thin wrapper around the browser’s API, lets you shrink the build to less than 10KB when minified and gzipped. See the for instructions on how to create a custom build, and remember that any plugins you use will also need to stick to the subset you select.

jQuery 1.9 API equivalence: jQuery 2.0 is API-compatible with 1.9, which means that all of the changes documented in the jQuery 1.9 Upgrade Guide have been applied to jQuery 2.0 as well. If you haven’t yet upgraded to jQuery 1.9, you may want to try that first. Be sure to use the .

The full record of changes can be found in the changelog below, and in the list of commits on GitHub.

Fixes

One bug worth highlighting is a bug we fixed in the Ajax script transport. jQuery used to evaluate any response to a request for a script as a script, which is not always the desired behavior. This is different than other data types where such a convention was fine (e.g. in the case of JSON). jQuery 3.5.0 will now only evaluate successful HTTP responses.

Other bug fixes and improvements include performance improvements in Sizzle, support for massive arrays in jQuery.map, using the native method where supported, a fix for syntax errors in the AMD modules, several improvements to our testing infrastructure, and more. You’ll find the full changelog below.

Quick start

Insert the following line on your HTML page and you are done!

<script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script>

HTML

This is the official jQuery Tools UI library and
after the inclusion you will have the following tools available:

  1. jQuery

The tools will be loaded
with maximum
performance no matter where your user is located on the
globe. Without the jQuery library, the file size is
only 4.45 Kb when gzipping is enabled on
the server-side. If you already have jQuery included on your page,
you can simply remove it and use only the above script
src
statement.

Please note that this global content delivery network
is completely free. You can use it freely in any
website including production environments. This network has been
kindly offered for all jQuery Tools users
by Max
CDN. Respect to them!

Latest stable version

1.4.5

ZIP file

If you want to host the files yourself you can download a zip of all the files:

Zip File: jquery.mobile-1.4.5.zip (JavaScript, CSS, and images)

jQuery CDN provided by MaxCDN

JavaScript:

  • Uncompressed: jquery.mobile-1.4.5.js (useful for debugging)
  • Minified and Gzipped: jquery.mobile-1.4.5.min.js (full library, ready to deploy)

CSS:

  • Uncompressed with Default theme: jquery.mobile-1.4.5.css (useful for debugging)
  • Minified and Gzipped with Default theme: jquery.mobile-1.4.5.min.css (full library, ready to deploy)
  • Uncompressed structure without a theme: jquery.mobile-1.4.5.css (useful for theme development)
  • Minified and Gzipped structure without a theme: jquery.mobile-1.4.5.min.css (to be used with custom theme and icon CSS, ready to deploy)

Copy-and-Paste snippet for jQuery CDN hosted files:

1

2

3

Google CDN

  • http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.js
  • http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js
  • http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.css
  • http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css

Microsoft CDN

Microsoft CDN – jQuery Mobile

Download

You can get the files from the jQuery CDN, or link to them directly:

You can also get this release from npm:

Slim build

Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version. These files are also available in the npm package and on the CDN:

These updates are already available as the current versions on npm and Bower. Information on all the ways to get jQuery is available at https://jquery.com/download/. Public CDNs receive their copies today, please give them a few days to post the files. If you’re anxious to get a quick start, use the files on our CDN until they have a chance to update.

jQuery Migrate — All Versions

  • jQuery Migrate 3.3.2 — uncompressed, minified
  • jQuery Migrate 3.3.1 — uncompressed, minified
  • jQuery Migrate 3.3.0 — uncompressed, minified
  • jQuery Migrate 3.2.0 — uncompressed, minified
  • jQuery Migrate 3.1.0 — uncompressed, minified
  • jQuery Migrate 3.0.1 — uncompressed, minified
  • jQuery Migrate 3.0.0 — uncompressed, minified
  • jQuery Migrate 1.4.1 — uncompressed, minified
  • jQuery Migrate 1.4.0 — uncompressed, minified
  • jQuery Migrate 1.3.0 — uncompressed, minified
  • jQuery Migrate 1.2.1 — uncompressed, minified
  • jQuery Migrate 1.2.0 — uncompressed, minified
  • jQuery Migrate 1.1.1 — uncompressed, minified
  • jQuery Migrate 1.1.0 — uncompressed, minified
  • jQuery Migrate 1.0.0 — uncompressed, minified

Как использовать jQuery на странице

Использование jQuery рассмотрим на простом HTML5 документе. Для этого мы его создадим, подключим к нему эту библиотеку с помощью Google CDN, и произведём с помощью неё ряд изменений на странице. А именно, изменим цвет фона на , выровняем по центру и добавим в конец страницы элемент с контентом «Я люблю jQuery».

<!doctype html>
<html lang="ru">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Страница, к которой подключен jQuery</title>
  <script defer src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <h1>Моя страница, к которой подключён jQuery</h1>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      /* код на jQuery */
      // установим body фон #eee
      $('body').css('background-color', '#eee');
      // выровняем h1 по центру
      $('h1').css('text-align', 'center');
      // добавим в конец страницы элемент div с контентом "Я люблю jQuery"
      $('body').append('<div style="text-align: center; font-size: 20px;">Я люблю jQuery</div>');
    });
  </script>
</body>
</html>

Синтаксис jQuery начинается с функции или с более короткого и красивого псевдонима — знака (как в этом примере).

Что делать при конфликте jQuery с другой библиотекой

Но что делать если знак у вас занят и используется другой библиотекой?

В этом случае, чтобы избежать конфликтов можно воспользоваться одним из следующих 3 способов.

1 способ: обращение к jQuery по её полному имени.

// вызываем метод noConflict
jQuery.noConflict();
// обращаемся к jQuery по её полному имени
jQuery('body').css('background-color', '#eee');
// ...

2 способ: обращение к jQuery по другому псевдониму, например .

// установка $j в качестве псевдонима функции jQuery
var $j = jQuery.noConflict();
$j('body').css('background-color', '#eee');
// ...

3 способ: обращение к jQuery по .

jQuery.noConflict();
(function($) {
  $(function() {
    /* код на jQuery */
    $('body').css('background-color', '#eee');
    // ...
  });
})(jQuery);
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector