Goodbye jQuery! Moving on to DOM and ES6 sprinkles
Posted LeWagon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Goodbye jQuery! Moving on to DOM and ES6 sprinkles相关的知识,希望对你有一定的参考价值。
Sebastien - CTO Le Wagon
Sebastien is a software engineer with more than 8 years of experience at Google. He is now teaching all you need to know about web programming and the technical workflow used in a startup.
6 min read.
Looking back in time, jQuery was created to cope with javascript implementation differences between browsers. Internet Explorer was the main culprit at that time and lagged behind Mozilla Firefox and then Google Chrome. As an easy to use solution, jQuery has been widely embraced by developers and beginners who, for the majority started to use JavaScript through this library.
In 2017, IE8 to IE11 usage have dropped to a very small part of web traffic and can be safely ignored. This means that we can now drop jQuery from our application and rely on standard DOM and some ES6 sprinkles.
Speed being one of the main criterias for SEO (and users), sparing our browser the effort of loading a whole library before processing our code offers a nice bonus we all should consider to get quickly!
Time for a change. For the better. Here's how...
1. Selecting DOM elements
Suppose you have the following HTML:
<div id="lead">lorem ipsum</div>
<ul> <li class="green">First item</li> <li class="red">Second item</li> <li class="green">Third item</li> <li class="red">Last item</li>
</ul>
<p class="green status">A great status</p>
Then in jQuery you would use the $() function in combination with some CSS selector to go and fetch the DOM elements.
var lead = $('#lead');
var firstRedItem = $('.red').eq(0);
var greenListItems = $('li.green'); // Adding `li` not to select the `p`.
The alternative is now to use three standard DOM methods:
getElementById
Element.querySelector
Element.querySelectorAll
const lead = document.getElementById('lead'); // ⚠️ no #
const firstRedItem = document.querySelector('.red');
const greenListItems = document.querySelectorAll('li.green');
You may have noticed that we used const over var. Moving forward using ES6, we won't use var anymore, but const or let. We'll use let when we want to reassign a variable, const otherwise:
let name = "George";
name = name + " Abitbol"; // `name` is being re-assigned.
console.log(name);
2. Inserting a DOM element
A classic usage of JavaScript would be to insert a new piece of content into the DOM. On a blog, an AJAX-powered comment section would insert the comment when it's submitted, without reloading the page.
<div id="comments"> <p class="comment">This was great!</p> <p class="comment">I loved it :)</p></div>
<form> <textarea id="commentContent"></textarea> <button>Post comment</button>
</form>
Using jQuery, this is how we would do it:
var commentContent = $('#commentContent').val(); // Skipping AJAX part
$('#comments').append('<p class="comment">' + commentContent + '</p>');
Now we'll rely on Element#insertAdjacentHTML and ES6 template literals:
const commentContent = document.getElementById('commentContent').value;
const comments = document.getElementById('comments');
comments.insertAdjacenthtml('beforeend', `<p class="comment">${commentContent}</p>`);
3. Updating CSS classes
Adding, removing or toggling a CSS class on a DOM element is something quite common in a JavaScript app. With jQuery, we would use:
$(selector).addClass('bold');
$(selector).removeClass('bold');
$(selector).toggleClass('bold');
And this would apply the change to all elements matching the given selector.
Without jQuery, you can use classList:
// For one element selected with `getElementById` or `querySelector`
element.classList.add('bold');
element.classList.remove('bold');
element.classList.toggle('bold');
// For multiple elements selected with `querySelectorAll`:
elements.forEach((element) => { element.classList.add('bold'); // etc.
});
See? We just used Array.forEach!
4. Event listeners
JavaScript lets your bring dynamic behavior to your webpage. The simplest example we can take is having an alert pop up when click on a button.
<button id="useless-btn">Click me!</button>
With jQuery, we would use the .on() method (or one of its shortcuts):
$('#useless-btn').on('click', function(event) { alert('Thanks for clicking!');
});
The modern DOM gives you addEventListener to play with:
const button = document.getElementById('useless-btn');
button.addEventListener('click', (event) => { alert('Thanks for clicking!');
});
To get information on the clicked element, you can use event.target inside the event listener callback. But what was that =>? Well, it is called an arrow function. Those are great to preserve this and get rid of the var that = this trick.
Wes Bos did a great post and video on the topic: http://wesbos.com/javascript-arrow-functions/
5. AJAX
When you want to do AJAX, the original implementation relies on XMLHttpRequest, but nobody wants to use that. jQuery solved this problem ten years ago introducing the $.ajax method with its two handy shortcuts $.get and $.post:
// GET request
$.ajax({ url: "https://swapi.co/api/people/", type: "GET" success: function(data) { console.log(data); }});
// POST request
const data = { name: "a name", email: "an@email.com" };
$.ajax({ url: url, type: "POST", data: data, success: function(data) { console.log(data); }});
With modern browsers, we can rely on fetch() which provides a nicer API than raw XMLHttpRequest.
// GET request
fetch("https://swapi.co/api/people/") .then(response => response.json()) .then((data) => { console.log(data); });
// POST request
const data = { name: "a name", email: "an@email.com" };
fetch(url, { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify(data)
})
.then(response => response.json())
.then((data) => { console.log(data);
});
You can notice the fetch() second argument is a hash using more straightforward key names. Parts of the HTTP request are outlined: the method (or verb), the headers and the body.
以上是关于Goodbye jQuery! Moving on to DOM and ES6 sprinkles的主要内容,如果未能解决你的问题,请参考以下文章
16 Go Concurrency Patterns: Timing out, moving on
Go并发模型:超时,继续(Timing out, moving on译文)
Go并发模型:超时,继续(Timing out, moving on译文)
The 2019 Asia Yinchuan First Round Online Programming F. Moving On