How to grasp and use the website jQuery The best time to
jQuery It's the most popular now JavaScript Tool library. According to statistics, 57.3% of websites around the world currently use it. That is to say, 6 of the 10 websites are used jQuery。 If you only look at websites using the tool library, this proportion will rise to an astonishing 91.7%. Although jQuery So popular, but its bloated size is also a headache. jQuery 2.0 The original size is 235 KB, Optimized to 81 KB; If it is supported IE6、7、8 of jQuery 1.8.3, Original size is 261 KB, Optimized to 91 KB。
Such volumes, even in broadband environments, take 1 second or more to fully load, not to mention mobile devices. This means, if you use jQuery, The user delays at least 1 second before the web page effect can be seen. In essence, jQuery Just an operation DOM We not only ask: if it is just for a few web page special effects, is it necessary to use such a large library?
2006 Year, jQuery When it was born, it was mainly used to eliminate the differences between different browsers (mainly IE6), Provide developers with a simple unified interface. Compared to that time, the situation has changed a lot today. IE The market share has been declining to ECMAScript Based on JavaScript Standard grammar is receiving increasingly widespread support. Developers use it directly JavScript Standard syntax can be run on major browsers at the same time, no longer required to pass jQuery Get compatibility.
Let's discuss how to use it well jQuery The best time to use JavaScript Standard grammar, replace jQuery Some of the main functions of jQuery-free。 How to do it jQuery-free?
1. Select DOM element
jQuery The core is to select the DOM Elements, can be used querySelectorAll Methods simulate this function.
var $ = document.querySelectorAll.bind (document);
What needs to be noted here is that querySelectorAll The method returns NodeList object, it's much like an array (with numeric indexes and length Properties), but not arrays, cannot be used pop、push Array-specific methods. If necessary, consider Nodelist Convert the object to an array.
myList = Array.prototype.slice.call (myNodeList);
two, DOM operate
DOM It has a rich operating method and can replace it jQuery Provided operation method.
Additional at the tail DOM element.
// jQuery How to write
$(parent) .append ($(child));
// DOM How to write
parent.appendChild (child)
Head insertion DOM element.
// jQuery How to write
$(parent) .prepend ($(child));
// DOM How to write
parent.insertBefore (child, parent.childNodes[0])
delete DOM element.
// jQuery How to write
$(child) .remove ()
// DOM How to write
child.parentNode.removeChild (child)
3. Monitoring of events
jQuery of on Method, can be used completely addEventListener simulation.
Element.prototype.on = Element.prototype.addEventListener;
For ease of use, you can NodeList This method is also deployed on the object.
NodeList.prototype.on = function (event, fn) {
[]['forEach'].call (this, function (el) {
el.on (event, fn);
});
return this;
};
4. Triggering of events
jQuery of trigger The method needs to be deployed separately, which is relatively complicated.
Element.prototype.trigger = function (type, data) {
var event = document.createEvent ('HTMLEvents');
event.initEvent (type, true, true);
event.data = data {};
event.eventName = type;
event.target = this;
this.dispatchEvent (event);
return this;
};
exist NodeList This method is also deployed on the object.
NodeList.prototype.trigger = function (event) {
[]['forEach'].call (this, function (el) {
el['trigger'](event);
});
return this;
};
five, document.ready
The current best practice is to JavaScript The script files are loaded at the bottom of the page. In this case, document.ready method( jQuery 简写为$(function))It's no longer necessary because when it's running, DOM The object has been generated.
six, attr method
jQuery use attr Method, read and write the properties of web page elements.
$("#picture") .attr ("src", "http://url/to/image");
DOM Elements allow direct reading of attribute values, and the writing is much simpler.
$("#picture") .src = "http://url/to/image";
Need to be careful, input Elemental this.value Returns the value in the input box, linking the element this.href The return is absolute URL。 If you need to use the exact attribute values of these two web page elements, you can use this.getAttribute (‘value’)and this.getAttibute (‘href’)。
seven, addClass method
jQuery of addClass Method, used for DOM Add an element class。
$('body') .addClass ('hasJS');
DOM The element itself has a readable and writeable className Properties, can be used to operate class。
document.body.className = 'hasJS';
// or
document.body.className += ' hasJS';
HTML 5 Also provide one classList Object, more powerful ( IE 9 Not supported).
document.body.classList.add ('hasJS');
document.body.classList.remove ('hasJS');
document.body.classList.toggle ('hasJS');
document.body.classList.contains ('hasJS');
eight, CSS
jQuery of css Method, used to set the style of web page elements.
$(node) .css ( "color", "red" );
DOM There is one element style Properties can be operated directly.
element.style.color = "red";;
// or
element.style.cssText += 'color:red';
9. Data storage
jQuery Objects can store data.
$("body") .data ("foo", 52);
HTML 5 There is one dataset Objects have similar functions ( IE 10 Not supported), but only strings can be saved.
element.dataset.user = JSON.stringify (user);
element.dataset.score = score;
ten, Ajax
jQuery of Ajax Method for asynchronous operation.
$.ajax ({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}) .done (function ( msg ) {
alert ( "Data Saved: " + msg );
});
We can define a request Function, simulation Ajax method.
function request (type, url, opts, callback) {
var xhr = new XMLHttpRequest ();
if (typeof opts === 'function') {
callback = opts;
opts = null;
}
xhr.open (type, url);
var fd = new FormData ();
if (type === 'POST' && opts) {
for (var key in opts) {
fd.append (key, JSON.stringify (opts[key]));
}
}
xhr.onload = function () {
callback (JSON.parse (xhr.response));
};
xhr.send (opts ? fd : null);
}
Then, based request Function, simulation jQuery of get and post method.
var get = request.bind (this, 'GET');
var post = request.bind (this, 'POST');
11. Animation
jQuery of animate Method, used to generate animation effects.
$foo.animate ('slow', { x: '+=10px' });
jQuery Most of the animation effects are based on DOM。 But for now, CSS 3 The animation is far more DOM Powerful, so you can write animation effects into CSS, Then through operation DOM Elemental class, To show the animation.
foo.classList.add ('animate');
If you need to use a callback function for the animation, CSS 3 The corresponding events are also defined.
el.addEventListener ("webkitTransitionEnd", transitionEnded);
el.addEventListener ("transitionend", transitionEnded);
12. Alternative Solutions
because jQuery The size is too large and alternatives are endless.
Among them, the most famous one is zepto.js。 Its design goal is to achieve maximum compatibility with the smallest size jQuery of API。zepto.js 1.0 The original size of the version is 55 KB, After optimization, it is 29 KB,gzip After compression, it is 10 KB。
If you do not seek maximum compatibility, you only want to simulate jQuery The basic functions, then, min.js Only 200 bytes after optimization, and dolla After optimization, it is 1.7 KB。
also, jQuery It adopts a module design, and you can only choose to use the modules you need. See its specific practices GitHub Website, or use a dedicated Web interface.

The above is the "How to grasp and use the website production and use it" shared by Suyou.com jQuery "The best time to read this article patiently. We will provide you with more information on reference or learning communication. We can also provide you with: Enterprise website construction, website imitation, website copying, imitation site, foreign trade website construction, foreign trade website construction, company official website productionFor services, our company serves customers with the service concept of "integrity, professionalism, pragmatism and innovation". If you need cooperation, please scan the code to consult, and we will serve you sincerely.