Jquery tutorial

если не использовать на сайте jquery-migrate.js

Это вторая строчка на картинке выше: (для чего это нужно, рассмотрим в следующей статье).

А исходный код таким:

Что нам и требовалось..!

Нота:

как понимаете, показанный способ цепляется из серверов Гугл и, конечно, самой актуальной версии..!

Некоторые веб мастера скачивают версию CDM и помещяют к себе на сервер (ядро сайта/шаблона) якобы сокращая время подгрузки библиотек, из-за «падений» серверов google — вряд ли, на мой взгляд, этот способ нынче оправдан: сомнительно, будто б наши хостинги надёжнее, нежели сервер(а) Гугле.

…но это так, к слову…

Если вам нужно подключить CDM от серверов гугл, но ту версию, которую использует на данный момент WordPress (это полезно, для тех, которые не обновляют WP) то вариант подключения будет выглядеть следующим образом:

jQuery Slim build

Иногда вам не нужно делать ajax запросы, или вы предпочитаете использовать отдельные библиотеки для этих целей, например request,axios, или модуль $http в AngularJS. По этому вместе с стандартной сборкой jQuery, которая содержит под модули ajax, и анимационных эффектов, предоставляется урезанная ‘slim’ версия. В наше время размер библиотеки jQuery кажется крошечным по сравнению с другими фреймворками и библиотеками, но все же можно уменьшить нагрузку на сервер используя slim сборку, которая весит всего 6kb при использовании gzip сжатия, обычная версия весит 24 килобайта.

https://code.jquery.com/jquery-3.3.1.slim.js https://code.jquery.com/jquery-3.3.1.slim.min.js

Изменения в jQuery 3.3.0

Теперь методы .addClass(), .removeClass(), и .toggleClass() принимают как параметр массив классов.

jQuery(‘section.main’).addClass();

Изменения в jQuery 3.2.0

Добавлена поддержка кастомных CSS свойств

<div style="--margin: 10px; margin: var(--margin)">
Some content
</div> 
<script>
$('div').css('--margin') ; // should return 10
$('div').css('--margin',20') ; // should change block margin to 20
</script>
  • Методы jQuery.holdReady,jQuery.nodeName,jQuery.isArray стали deprecated
  • Исправлена ошибка в методах .width(), .height() и других связанных методах где учитывались CSS transforms свойства. Например, елемент со стилем transform: scale(3x) не должен иметь высоту и ширину в три раза больше.
  • Добавлена поддержка элемента <template> в методе .contents().
let deferred = jQuery.Deferred();
deferred.then(function() {
console.log("first promise");
throw new Error("Some error occured");
})
.then(function() {
console.log("second promise");
}, function(err) {
console.log("rejection promise", err instanceof Error);
});
deferred.resolve();

Изменения в jQuery 3.0

jQuery.Deferred теперь совместим с Promises/A+

Объекты класса jQuery.Deferred теперь совместимы с Promises/A+ и промисами ES2015. Всем кто использовал этот метод ранее, нужно будет внести изменения, или заменить его на метод pipe. Также исключение выброшено в колбек .then() теперь становится значением reject. Все объекты deferred которые базировались на то что будет выброшено исключения никогда не будут выполены (resolved).

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

Колбеки будут выполняться асинхронно, не смотря на то Deferred был resolved

let defer = jQuery.Deferred();
defer.resolve();
defer.then(function() {
    console.log("success message");
});
console.log("after message");

Раньше в консоль бы вывелось «success message» потом «after message», а в последней версии наоборот.

К Deferred был добавлен метод catch()

Анимации теперь используют requestAnimationFrame В браузерах что поддерживают requestAnimationFrame будет использоваться это API для управления анимациями. Что уменьшит использование ресурсов CPU и увеличит время работы батареи на мобильных устройствах

  • Увеличена производительность кастомных селекторов.
  • Для некоторых селектора например таких как :visible скорость работы была увеличена в 17 раз

Просмотры:
7 950

 

AJAX Example Explained

HTML Page

<!DOCTYPE html><html>
<body>
<div id=»demo»>  <h2>Let AJAX change this text</h2> 
<button type=»button» onclick=»loadDoc()»>Change Content</button>
</div>
</body>
</html>

The HTML page contains a <div> section and a <button>.

The <div>
section is used to display information from a server.

The <button> calls a function (if it is clicked).

The function requests data from a web
server and displays it:

Function loadDoc()

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {   
if (this.readyState == 4 && this.status == 200) {    
document.getElementById(«demo»).innerHTML = this.responseText;   
}  };  xhttp.open(«GET», «ajax_info.txt», true); 
xhttp.send();
}

«ajax_info.txt» looks like this:

<h1>AJAX</h1><p>AJAX is not a programming language.</p><p>AJAX is a
technique for accessing web servers from a web page.</p><p>AJAX stands for
Asynchronous JavaScript And XML.</p>

link Downloading jQuery

Compressed and uncompressed copies of jQuery files are available. The uncompressed file is best used during development or debugging; the compressed file saves bandwidth and improves performance in production.
You can also download a sourcemap file for use when debugging with a compressed file.
The map file is not required for users to run jQuery, it just improves the developer’s debugger experience.
As of jQuery 1.11.0/2.1.0 the comment is not included in the compressed file.

To locally download these files, right-click the link and select «Save as…» from the menu.

jQuery

For help when upgrading jQuery, please see the upgrade guide most relevant to your version.
We also recommend using the jQuery Migrate plugin.

You can also use the slim build, which excludes the ajax and effects modules:

Why using jQuery CDN is good for your website

When you use jQuery CDN then you are actually doing 2 positive things:

  • 1. Decreasing the load on your website since the jQuery file will be loaded from a CDN and not from your website.
  • 2. jQuery loads faster from CDNs than from your website. This is because CDNs are made for speed, they serve jQuery from the nearest position to the users. They also have lots of data servers and load balancing algorithms that make sure the jQuery is served very fast.

The article What is CDN? explains all about CDN from starting to the end. Do check it.

There can be issues when loading jQuery from CDNs

a. The CDN hosted jQuery might be blocked by a filter or proxy service on the user’s connnection.b. The CDN is down or timing out, since the browsers typically have a timeout of 30 seconds therefore the jQuery fails to load in these conditions.

Falling Back from CDN to Local Copy of jQuery present on the Website

Luckily there is a simple solution for these CDN issues. You can easily provide a locally-hosted fallback version of jQuery. The basic idea for CDN fallback is to check for a type or variable that should be present after a script loads. If it’s not there then try getting the jQuery file locally.

Notice the escape characters inside the document.write method.

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script>
    if (typeof jQuery == 'undefined') {
        document.write(unescape("%3Cscript src='/js/jquery-3.2.1.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
</script>

Or, slightly differently.

// First try loading jQuery from CDN
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 
// If the CDN fails then Fallback to a local copy of jQuery 
<script>
    window.jQuery || document.write('<script src="/js/jquery-3.2.1.min.js"><\/script>'))
</script>

jQuery Selectors

Use our jQuery Selector Tester to demonstrate the different selectors.

Selector Example Selects
* $(«*») All elements
#id $(«#lastname») The element with id=»lastname»
.class $(«.intro») All elements with class=»intro»
.class,.class $(«.intro,.demo») All elements with the class «intro» or «demo»
element $(«p») All <p> elements
el1,el2,el3 $(«h1,div,p») All <h1>, <div> and <p> elements
     
:first $(«p:first») The first <p> element
:last $(«p:last») The last <p> element
:even $(«tr:even») All even <tr> elements
:odd $(«tr:odd») All odd <tr> elements
     
:first-child $(«p:first-child») All <p> elements that are the first child of their parent
:first-of-type $(«p:first-of-type») All <p> elements that are the first <p> element of their parent
:last-child $(«p:last-child») All <p> elements that are the last child of their parent
:last-of-type $(«p:last-of-type») All <p> elements that are the last <p> element of their parent
:nth-child(n) $(«p:nth-child(2)») All <p> elements that are the 2nd child of their parent
:nth-last-child(n) $(«p:nth-last-child(2)») All <p> elements that are the 2nd child of their parent, counting from the
last child
:nth-of-type(n) $(«p:nth-of-type(2)») All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n) $(«p:nth-last-of-type(2)») All <p> elements that are the 2nd <p> element of their parent, counting from the
last child
:only-child $(«p:only-child») All <p> elements that are the only child of their parent
:only-of-type $(«p:only-of-type») All <p> elements that are the only child, of its type, of their parent
     
parent > child $(«div > p») All <p> elements that are a direct child of a <div> element
parent descendant $(«div p») All <p> elements that are descendants of a <div> element
element + next $(«div + p») The <p> element that are next to each <div> elements
element ~ siblings $(«div ~ p») All <p> elements that appear after the <div> element
     
:eq(index) $(«ul li:eq(3)») The fourth element in a list (index starts at 0)
:gt(no) $(«ul li:gt(3)») List elements with an index greater than 3
:lt(no) $(«ul li:lt(3)») List elements with an index less than 3
:not(selector) $(«input:not(:empty)») All input elements that are not empty
     
:header $(«:header») All header elements <h1>, <h2> …
:animated $(«:animated») All animated elements
:focus $(«:focus») The element that currently has focus
:contains(text) $(«:contains(‘Hello’)») All elements which contains the text «Hello»
:has(selector) $(«div:has(p)») All <div> elements that have a <p> element
:empty $(«:empty») All elements that are empty
:parent $(«:parent») All elements that are a parent of another element
:hidden $(«p:hidden») All hidden <p> elements
:visible $(«table:visible») All visible tables
:root $(«:root») The document’s root element
:lang(language) $(«p:lang(de)») All <p> elements with a lang attribute value starting with «de»
     
$(«») All elements with a href attribute
$(«») All elements with a href attribute value equal to «default.htm»
$(«») All elements with a href attribute value not equal to «default.htm»
$(«») All elements with a href attribute value ending with «.jpg»
[attribute|=value] $(«») All elements with a title attribute value equal to ‘Tomorrow’, or starting
with ‘Tomorrow’ followed by a hyphen
[attribute^=value] $(«») All elements with a title attribute value starting with «Tom»
[attribute~=value] $(«») All elements with a title attribute value containing the specific word «hello»
[attribute*=value] $(«») All elements with a title attribute value containing the word «hello»
     
:input $(«:input») All input elements
:text $(«:text») All input elements with type=»text»
:password $(«:password») All input elements with type=»password»
:radio $(«:radio») All input elements with type=»radio»
:checkbox $(«:checkbox») All input elements with type=»checkbox»
:submit $(«:submit») All input elements with type=»submit»
:reset $(«:reset») All input elements with type=»reset»
:button $(«:button») All input elements with type=»button»
:image $(«:image») All input elements with type=»image»
:file $(«:file») All input elements with type=»file»
:enabled $(«:enabled») All enabled input elements
:disabled $(«:disabled») All disabled input elements
:selected $(«:selected») All selected input elements
:checked $(«:checked») All checked input elements
Добавить комментарий

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