How to do web site do not need to complete the jQuery

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

JQuery is now the most popular JavaScript tool library.

According to statistics, 57.3% of the world's Web site to use it. That is to say, 10 sites, 6 using jQuery. If only the use of tool library website, this proportion will rise to a staggering 91.7%.


Although the jQuery is so popular, but its bloated size is also a headache for the people. The original size of jQuery 2 is 235KB, optimized for 81KB; if it is to support IE6,7,8 jQuery 1.8.3, the original size is 261KB, the optimized 91KB.

This volume, even if is a broadband environment, fully loaded also needs one second or longer, not to speak of a mobile device. This means, if you use jQuery, the user at least delay of 1 second, can see the webpage effect. Taking into account the essence, jQuery is a tool operating DOM, we not only have to ask: if only for a few webpage specially good effect, whether it is necessary to use such a big library?


In 2006, jQuery was born, which is mainly used to eliminate differences in different browsers (IE6), to provide a unified interface and simple for developers. Compared at that time, now the situation has undergone great changes. IE's market share is declining, the grammar of JavaScript standard based on ECMAScript, is being more and more widely support. Developers using the JavScript standard grammar, can also run in the browser, no longer need to obtain the compatibility with jQuery.

Here is how to use the JavaScript standard grammar, some main functions instead of jQuery, do jQuery-free.


A, select DOM element

The core of jQuery is through a variety of selector, select the DOM element, can simulate the function with querySelectorAll method.

var $ = document.querySelectorAll.bind(document);

It should be noted that, querySelectorAll returns the NodeList object, it is very much like an array (Digital index and the length property), but is not an array, you cannot use the pop, push array of unique method. If necessary, can be considered to be a Nodelist object to an array.

myList = Array.prototype.slice.call(myNodeList);

In two, DOM operation

DOM itself has the operation method is very rich, can replace the jQuery provides the operation method.

The addition of DOM element in the tail.

// JQuery writing

$(parent).append($(child));

// DOM writing

parent.appendChild(child)

The head is inserted into the DOM element.

// JQuery writing

$(parent).prepend($(child));

// DOM writing

parent.insertBefore(child, parent.childNodes[0])

Remove the DOM element.

// JQuery writing

$(child).remove()

// DOM writing

child.parentNode.removeChild(child)

Three, event monitor

The on method of the jQuery, can use addEventListener simulation.

Element.prototype.on = Element.prototype.addEventListener;

In order to facilitate the use of this method, can be deployed in the NodeList object.

NodeList.prototype.on = function (event, fn) {

[]['forEach'].call(thisfunction (el) {

el.on(event, fn);

});

return this;

};

Four, the event triggering

Trigger jQuery requires a separate deployment, some relatively complex.

Element.prototype.trigger = function (type, data) {

var event = document.createEvent(‘HTMLEvents’);

event.initEvent(type, truetrue);

event.data = data || {};

event.eventName = type;

event.target = this;

this.dispatchEvent(event);

return this;

};

This method is also deployed in the NodeList object.

NodeList.prototype.trigger = function (event) {

[]['forEach'].call(thisfunction (el) {

el['trigger'](event);

});

return this;

};

Five,document.ready

Current best practice, is the JavaScript script file is loaded in the bottom of the page. So, in fact, the document.ready method (jQuery or $(function)) is not necessary, because until run time, the DOM object has been generated.

Six, the attr method

JQuery uses the attr method to write, read attribute webpage elements.

 $(“#picture”).attr(“src”, ”http://url/to/image”);

The DOM element allows to directly read the value of a property, writing should be simple and many.

$(“#picture”).src = ”http://url/to/image”;

Need to pay attention to the input element, this.value returns the value in the input box, link element returned by this.href is URL. If the property need to use these two webpage elements accurate value, you can use this.getAttribute (‘ value’) and this.getAttibute(‘href’).

Seven, the addClass method

The addClass method of the jQuery, used to add a class DOM element.

$(‘body’).addClass(‘hasJS’);

The DOM element has a className attribute of read and write, can be used to operate class.

document.body.className = ’hasJS’;

// or

document.body.className += ’ hasJS’;

HTML 5 also provides a classList object, more powerful (IE 9 does not support).

document.body.classList.add(‘hasJS’);

document.body.classList.remove(‘hasJS’);

document.body.classList.toggle(‘hasJS’);

document.body.classList.contains(‘hasJS’);

Eight,CSS

CSS jQuery, used to set the webpage elements.

$(node).css( ”color”, ”red” );

The DOM element has a style attribute, you can directly manipulate.

element.style.color = ”red”;;

// or

element.style.cssText += ’color:red’;

Nine, data storage

The jQuery object can be used to store data.

$(“body”).data(“foo”, 52);

HTML 5 is a dataset object, also has a similar feature (IE 10 does not support), but can only save string.

element.dataset.user = JSON.stringify(user);

element.dataset.score = score;

Ten,Ajax

Ajax jQuery, 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, Ajax simulation.

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 on the function of request, get and post simulation jQuery.

var get = request.bind(this, ’GET’);

var post = request.bind(this, ’POST’);

Eleven, animation

Animate jQuery, used to generate the animation effect.

$foo.animate(‘slow’, { x: ’+=10px’ }),

JQuery animation, is largely based on DOM. However, CSS 3 than DOM strong animation, so the animation can be written into the CSS, and then through the operation of the DOM element of the class, to display animation.

foo.classList.add(‘animate’),

If you need to use a callback function to animation, CSS 3 also defines the corresponding event.

el.addEventListener(“webkitTransitionEnd”, transitionEnded);

el.addEventListener(“transitionend”, transitionEnded);

Twelve, alternatives

Because the jQuery volume is too large, the alternative emerge in an endless stream.

Among them, the most famous is zepto.js. Its design goal is to minimize the volume, do the most compatible with jQuery API. The original size of zepto.js version 1 is 55KB, the optimized 29KB, gzip compression for 10KB.

If not for maximum compatibility, only hope that the basic function, simulation jQuery, min.js optimization after only 200 bytes, but after the optimization of dolla is 1.7KB.

In addition, the jQuery itself features a modular design, can only choose to use their own needs module. Specific practices. See Synonyms at its GitHub web site, or use special Web interface.

Reprinted from

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Bard at November 12, 2013 - 7:55 PM