jQuery for the script guy

jQuery is the most used Javascript library in the world. It’s also one of the most hated. jQuery like all libraries has it’s advantages: it’s simple to use, is cross browser compatible and makes web pages interactive with only a few lines of code. Sounds great right? Only problem is that it impacts website performance!
To begin, in order to use jQuery you need to add an external javascript file like ‘jquery.min.js’ which is a 30kb file. This file load time can add 7 milliseconds of delay to your page load, this might not sound like a lot but imagine a user with slow internet or mobile connection.
If you’ve added the library using google’s jQuery url ‘https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js’ then this would normally already be cached in the browser because a lot of website use jquery. Still though a delay is a delay.
Excluding the delay from the external file, jQuery is a lot slower than pure javascript or ‘vanilla’ javascript as it’s known in the industry. Even a simple task like adding a node to the DOM (Document Object Model) instead of a simple api call, jQuery performs multiple unnecessary operations for changing the DOM.
So what alternatives are there, other than re-writing your jquery functions in pure javascript, which is supported by all modern browsers, an alternative is to use a lightweight alternative such as Cash.
Pure Javascript examples for common jquery functions.
JavaScript Get Request
1234567891011121314 var request = new XMLHttpRequest();request.open('GET', '/my/url', true);request.onload = function() {if (request.status >= 200 && request.status < 400) {// Success!var resp = request.responseText;} else {// We reached our target server, but it returned an error}};request.onerror = function() {// There was a connection error of some sort};request.send();
JavaScript POST
12345 var request = new XMLHttpRequest();request.open('POST', '/my/url', true);request.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');request.send(data);
JavaScript Hide & Show
12 el.style.display = 'none';//HIDEel.style.display = '';//SHOW
JavaScript Find
1 el.querySelectorAll(selector);
JavaScript Append
1 parent.appendChild(el);
JavaScript Remove
1 el.parentNode.removeChild(el);
JavaScript Get Html
1 el.innerHTML
JavaScript Get Text
1 el.textContent
JavaScript Set Style
1 el.style.borderWidth = '20px';
JavaScript Set Html
1 el.innerHTML = string;
JavaScript Add Class
1234 if (el.classList)el.classList.add(className);elseel.className += ' ' + className;
JavaScript Remove Class
123456 if (el.classList)el.classList.remove(className);elseel.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|')+ '(\\b|$)', 'gi'), ' ');