How to add jquery to html
How to add jquery to html
Что такое jQuery? Как его скачать и подключить к сайту?
В этой статье вы узнаете: что такое JavaScript библиотека jQuery, как скачать последнюю версию и подключить её к сайту, как установить скрипт с Google CDN и других хранилищ на страницу, а также чем отличается обычная версия от slim и сжатая от не сжатой.
Что такое jQuery и её поддержка браузерами
jQuery — это быстрая, лёгкая и многофункциональная JavaScript библиотека, основанная на принципе «пиши меньше, делай больше».
Её создал Джон Резиг в начале 2006 года. В настоящее время jQuery разрабатывается и поддерживается распределенной группой разработчиков как проект с открытым исходным кодом.
Сейчас последней версией jQuery является 3.5.1. Она поддерживается во всех основных браузерах: Chrome, Firefox, Safari, Edge, Opera и Internet Explorer 9+.
Преимущества и недостатки jQuery
Преимущества, которые даёт нам библиотеки jQuery при её использовании для написания клиентских сценариев:
Кроме преимуществ, приведённых выше, у библиотеки jQuery имеются конечно и недостатки.
К недостаткам jQuery можно отнести то, что она может немного увеличивать скорость загрузки веб-страницы (её сжатый размер составляет около 30КБ), а также немного снижать производительность выполнения кода, чем если он был бы написан на чистом JavaScript.
Статистика использования jQuery
Если перейти к статистике, то многие крупные компании, используют jQuery в своих приложениях и сайтах. При этом растущий тренд продолжается, несмотря на очень горячие дискуссии в ИТ сообществах на тему: «Стоит ли использовать jQuery или нет в 2021 году?»
Что можно делать с jQuery
jQuery позволяет очень легко:
Этот список можно продолжить дальше, т.к. jQuery содержит большое количество функций, которые значительно упрощают написание кода для решения различных задач, стоящих перед веб-разработчиками.
Как скачать jQuery
Скачать бесплатно библиотеку jQuery можно с официального сайта.
Кроме этого, каждая из них доступна нам как в сжатом (с суффиксом min ) так и в несжатом виде.
Несжатый вариант библиотеки рекомендуется использовать только во время разработки проекта или его отладки. Кроме этого, его ещё используют для изучения исходного кода jQuery. В нём можно посмотреть устройство как всей библиотеки, так и определённой функции.
На продакшене лучше применять сжатый вариант jQuery (с расширением min.js ). Он меньше весит, и, следовательно, быстрее загружается. А это очень важно для производительности сайта.
Уменьшение объема JavaScript кода библиотеки jQuery осуществляется за счёт минимизации. Минимизация – это процесс, который заключается в удалении из исходного кода всего лишнего (комментариев, незначащих пробелов, переносов строк, символов табуляции) и замене имен функций и переменных на более короткие.
jQuery 1.x следует использовать если нужна поддержка IE 6 – 8.
jQuery 2.x построено на том же API, что 1.x. Но имеет меньший размер и более высокую производительность. Это было достигнуто благодаря тому, что из неё был удалён устаревший код, необходимый для поддержки IE 6 – 8. Таким образом 2.x можно использовать только в том случае, если вам не нужна поддержка этих старых браузеров.
После того как вы определись какой вариант библиотеки вам нужен, его необходимо загрузить.
Для скачивания jQuery с официального сайта нажмите правой кнопкой мыши на нужную ссылку и выберите пункт «Сохранить ссылку как. ».
Как подключить скрипт jQuery в html
Подключение jQuery к странице осуществляется также как и любого другого JavaScript файла. Т.е. посредством добавления в HTML тега
How to link jQuery in HTML page?
What is jQuery?
jQuery is a fast and concise JavaScript library primarily designed with a nice motto − Write less, do more. The main purpose of this library is to make it easier to use JavaScript on our website. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery wraps many lines of JavaScript code into methods that we can call with a single line of code.
How to link jQuery?
1. By downloading the jQuery library locally
Download the latest version of jQuery library from the official website https://jquery.com/download/. You can download any of the four types of available jQuery versions- uncompressed, minified, slim and slim & minified.
Now put the downloaded jquery-3.6.0.min.js file in a directory of your website, e.g. /jquery.
We can link jQuery in an HTML page by using a script tag and providing the downloaded jQuery library file address as the src attribute. The jquery-3.6.0.min.js can be added like below.
Let’s understand with the help of a complete example.
Example
In the example below we include jQuery library in our HTML page as follows –
Output
2. By including the jQuery from a CDN
We can link the jQuery library in our HTML page directly from a Content Delivery Network. There are different CDNs that provide the latest version of the jQuery library. For Example, Google, Microsoft, Cloudflare CDNs, and jQuery’s own CDN.
Let’s understand how to link jQuery from these CDNs each with help of examples.
Example #1 − Link jQuery from Google CDN
We can link jQuery in an HTML page by using a script tag and providing a jQuery Google CDN address as the src attribute. The jquery.min.js can be added like below.
Here, in the example below we link the jQuery library in our HTML page as follows −
Output
Here the fadeIn() method changes the opacity, for selected elements, from hidden to visible. It is to specify the speed of the fading effect, which can be slow or fast.
Example #2 − Link jQuery from Microsoft CDN
We can link jQuery in an HTML page by using a script tag and providing a jQuery Microsoft CDN address as the src attribute. The jquery-3.6.0.js can be added like below.
Here, in the example below we link the jQuery library from Microsoft CDN in our HTML page −
Output
When you click on the “Show Message” button, the message will be displayed.
Example #3: Link jQuery from Cloudflare CDN
We can also use Cloudflare CDN to link the jQuery library to our HTML page. To link jQuery in an HTML page we add jQuery Cloudflare CDN address to the src attribute of the script tag. The jquery.min.js can be added like below.
Here, in the example below we link the jQuery library from Cloudflare CDN in your HTML page −
Output
Example #4 − Link jQuery from jQuery CDN
We can also use jQuery CDN to link the jQuery library in our HTML page. To link jQuery in an HTML page we add the jQuery CDN address to the src attribute of the script tag. We also have to add integrity and crossorigin to the script. We can directly copy the script code from the jQuery website. jquery-3.6.0.min.js can be added like below-
Here, in the example below we link the jQuery library from jQuery CDN in your HTML page −
Как подключить библиотеку jQuery
В этой заметке речь пойдёт о том, как подключить библиотеку jQuery различными способами и как проверить корректность её работы. jQuery это такая очень полезная штуковина, которая представляет из себя комплект функций, упрощающих труд разработчика по созданию кода на языке программирования JavaScript. При помощи этой библиотеки скриптов вебмастер имеет возможность создать очень функциональный и визуально привлекательный сайт.
Вот какое определение библиотеки jQuery содержится на официальном сайте :
jQuery — это быстрая, небольшая и многофункциональная библиотека JavaScript. Она позволяет сделать намного проще такие вещи, как обход и манипулирование документами HTML, обработку событий, анимацию и Ajax, благодаря простому в использовании API, который работает во множестве браузеров. Благодаря сочетанию универсальности и расширяемости, jQuery изменил способ, которым миллионы людей пишут JavaScript.
Попробуем подключить jQuery и проверить на корректность работы.
Подключение jQuery в HTML
Чтобы в дальнейшем подключать актуальную версию jQuery, просто снова заходим на их офсайт и копируем адрес ссылки, как на скриншоте ниже. Далее, меняем ссылку в скрипте не актуальную.
Кроме того, можно включить в работу jQuery с CDN Google. Вместо вышеприведённой строчки внести запись:
Подключение jQuery с помощью файла js
Этот способ предусматривает копирование файла с актуальной версией jQuery на свой сервер. На главной странице официального сайта кликнуть по кнопке, как указано на скриншоте.
Появятся ссылки для скачивания. Лучше взять сжатую версию, так как она меньше весит, но работает точно также как и несжатая.
Этот файл закидываем в папку со своим сайтом. Можно создать для файла отдельную папку, например, js, если её до сих пор нет.
Теперь подключим js-файл. Для этого, опять же перед закрывающим тегом head, запишем:
Здесь важно правильно прописать путь к файлу jquery-3.5.1.js. Если он лежит прямо в корневом каталоге сайта вне каких-либо папок, то код скрипта будет выглядеть так:
С помощью файла functions.php
И ещё один альтернативный способ подключения jQuery предложен Kama, который считает, что его вариант наиболее правильный. Суть заключается в том, что в WordPress уже есть программный метод добавления скриптов на страницу при помощи функций, например:
wp_register_script()
wp_enqueue_script()
wp_deregister_script()
Такой метод предотвращает конфликты, когда один и тот же скрипт подключается разными плагинами. Это облегчает работу при оптимизации загрузки js файлов, что уменьшает время загрузки страниц сайта. В этом случае, скрипты можно объединить в один файл. А браузер получит их в сжатом виде.
Для правильного подключения jQuery надо воспользоваться функцией wp_enqueue_script(). Скрипт в данном случае подключается один раз. Файл functions.php необходимо дополнить такими строками:
add_action( ‘wp_enqueue_scripts’, ‘my_scripts_method’ );
function my_scripts_method() <
wp_enqueue_script( ‘jquery’ );
>
Теперь, если посмотреть исходный код страницы, то в head появится следующая запись:
Можно ли подключить jQuery по этому способу с CDN Google? Отличная новость — да! Вот этот код от Kama совершит чудо:
add_action( ‘wp_enqueue_scripts’, ‘my_scripts_method’ );
function my_scripts_method() <
// отменяем зарегистрированный jQuery
// чтобы отменить jquery-migrate, вместо «jquery-core» вписать «jquery»
wp_deregister_script( ‘jquery-core’ );
wp_register_script( ‘jquery-core’, ‘//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js’);
wp_enqueue_script( ‘jquery’ );
>
Его снова вписываем в файл functions.php. Результат работы кода:
Когда jquery-migrate.js не требуется, но нужен только jQuery, то следует дополнить functions.php таким кодом:
add_action( ‘wp_enqueue_scripts’, ‘my_scripts_method’ );
function my_scripts_method() <
// отменяем зарегистрированный jQuery
wp_deregister_script(‘jquery-core’);
wp_deregister_script(‘jquery’);
// регистрируем
wp_register_script( ‘jquery-core’, ‘https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js’, false, null, true );
wp_register_script( ‘jquery’, false, array(‘jquery-core’), null, true );
// подключаем
wp_enqueue_script( ‘jquery’ );
>
В этом случае увидим лишь такую строку в head:
В строке 9 «true» означает что скрипт подключится, по возможности, в футер сайта.
И ещё один вариант подключения той версии jQuery, которую использует WordPress. Вот код:
Как проверить работу jQuery на сайте
В сети нашёл несколько вариантов скриптов для этой цели:
Как это работает? Если jQuery подключена, то при переходе на любую страницу своего сайта, мы увидим надпись: «Этот текст добавлен с помощью jQuery».
Ещё один вариант скрипта:
Если jQuery не работает, то увидим такое сообщение: «jQuery не подключен».
Есть и более простой способ проверить правильность подключения jQuery. При помощи клавиши F12 вызвать консоль браузера и выполнить следующую команду:
Если увидели цифры, то это и есть версия подключенной jQuery.
Learning jQuery
How To Add jQuery To HTML?
HTML, CSS, and JavaScript are the three fundamental languages for designing any website. We structure our websites with HTML code, style them with CSS, and add various functionalities with the help of JavaScript.
jQuery is a widely used JavaScript library. With the help of an easy-to-use API that works across a multitude of browsers, jQuery makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler and easier. It simplifies client-side scripting of HTML.
Where To Put jQuery In HTML?
jQuery lets you perform actions in less code as compared to JavaScript. It is quite popular among the developers because of its simplicity, compatibility, flexibility, amazing effects, and ease in adding code to the HTML file. jQuery is embedded into the
Step 3: And finally save your HTML file and you can see that the jQuery file is successfully added into our Html page.
Let’s understand with an example:
Here’s what the output will be:
2. Including the jQuery by CDN.
Another method to include your jQuery to Html is including the jQuery by CDN(Content Delivery Network). It is very easy to implement by using CDN using the following steps.
Step 1: Open the HTML file in which you want to add your jQuery with the help of CDN.
Step 3: After that, you have to add the following path in the src attribute of the script tag.
Step 4: Save your HTML file and your jQuery is successfully added.
Let’s see how this is done:
Conclusion
In this tutorial, we learned how to add jQuery to HTML. We saw two different ways of doing it. The first one is by adding a jQuery file and the second is by CDN. Javascript and HTML are two integral parts of modern web development. Since jQuery is just a Javascript library it becomes important for any web developer to learn how to add jQuery to HTML.
To keep learning such interesting topics, subscribe to our blog!
To know more about what is jQuery used for, visit our previous article!
How to Use a JavaScript Library: jQuery
Learn how to dynamically change a website with the jQuery library
Read the article or watch the video!
JQuery is a library that contains lots of methods which make it much easier to manipulate HTML documents, add animation, along with a bunch of other things. Since JQuery is a library, it has an API that we can use to access its functionality.
API stands for Application Programming Interface and it basically states the methods or functions we can call inside our code if we import the library.
To start, we first need to create an index.html and a script.js file. We’ll also put the script.js file in a folder named js and then link our script.js file in our index.html file. This should look pretty familiar since we’ve done it in other tutorials.
Just like we imported bootstrap in the bootstrap tutorial, we need to import jQuery in this post. We can either download it from the Internet and link it locally or we can link it from the Internet. We’ll do the second and after searching for the jQuery CDN, we’ll add it to our code.
Make sure to add it above the our script.js link because we will need to use jQuery in this file. With our jQuery in place, we’ll add one line of HTML code, a header. We’ll add some styling that puts it in the center of the page and gives it a white text color. We can also give it the id hidden and the header will say “I was hidden!”.
Now, when we refresh the page, we’ll see that the header text is there, but we can’t see it unless we highlight it.
With jQuery and CSS, we could make it so that when we hover over it, the text of the header becomes black. To do this, we’ll go into our script.js file and write some code.
Here, the ready function makes sure that the DOM (for now, our HTML elements) have loaded. Once they are loaded, we select our element with the hidden id and call the hover function on it. This means when we over hover the element, the function on lines 2–4 will be run. The function will select “this” element (the element with the id hidden) and in the element’s CSS, the color property will be set to the value black. You could do this for any element, ID, or class and set any property to any value. Next, we have the callback function on lines 5–6 and this is something you have to write out even if you don’t use it. We will leave it empty for now and come back to it later.
Now, when we refresh the page and hover over the header, the text turns black. However, when we stop hovering over the header, the text remains black. What if we want to “re-hide” our message after hovering over it? Going back to the code we can implement our callback function. This will be called once we “leave” or stop hovering over our header, the element with the ID hidden. Let’s add some more code.
We hover over the header and leave it. After, the header element is gone — even when we try highlighting it, it cannot be found. With this program, we hid a message in plain sight, displayed the message while the mouse was pointed on it, and then made it disappear when the mouse left it.
For another quick example, we’ll add a button back in our HTML and make it so an alert shows up on the page when we click the button.
Now, we’ll write the JavaScript using the jQuery library to make the button interactive.
Here, we select all the buttons on the page and when one is clicked, we run the function. The function uses the alert method (built into HTML) to alert the user on screen with the message “I’m alerting you!”. Going back to our webpage, we’ll refresh and see what our alert looks like.