Goodbye to jQuery as dependency on Rails

Goodbye to jQuery as dependency on Rails

Allan Porras
Allan Porras Jul 26 2017 • 2 min read
Share:

One of the most popular Javascript libraries was used as a dependency on Rails and has a lot to do with the opinions of its creator who believes that most of the front-end needs could be met using a library like jQuery.

Why did Rails use it?

This library was used for some “rails-ujs” functionality which is a dependency of Rails to perform some basic actions without the need to refresh the browser.

In Rails 5.1, “rails-ujs” was rewritten using pure Javascript, so the dependency on jQuery no longer makes sense.

Unlike projects with previous versions the application.js file no longer needs:

//= require jquery
//= require jquery_ujs

And replaces it with

//= require rails-ujs

Of course, if we consider that jQuery is sufficient for our needs of Javascript the only thing we have to do is add it to the Gemfile and proceed as if nothing had happened or use the new rails package manager:

Install yarn on Mac:

brew install yarn

Add jQuery to Rails project, run the command from Rails home directory:

yarn add jquery

Add:

//= require jquery/dist/jquery

in application.js. It will look like:

//= require rails-ujs 
//= require turbolinks
//= require jquery/dist/jquery
//= require_tree .

Let’s look at some of the most common events:

For this case create a div with 4 elements a

<h1>List</h1> 
<div id="items">
<a href="" id="item1">Item 1</a>
<a href="" id="item2">Item 2</a>
<a href="" id="item3">Item 3</a>
<a href="" id="item4">Item 4</a>
</div>

Selecting elements

// jQuery version
$("#items")

// Javascript version
document.querySelector("#items") // returns the first matching element
document.querySelectorAll("#items a") // returns an array of elements

document.getElementById("items") // returns a single element

document.getElementsByTagName("a") // returns an array of elements

document.querySelector("#items").querySelectorAll("a") // returns an array of sub-elements from the first query

Adding Event Listeners

// jQuery version
$("a").on("click", function(event) {
event.preventDefault()
console.log("clicked")
})

// Javascript version
document.querySelectorAll.forEach(function(item) {
item.addEventListener("click", function(event) {
event.preventDefault()
console.log("clicked")
})
})

Hiding Elements

// jQuery version
$("#items").hide()
$("#items").show()

// Javascript version
document.querySelector("#items").style.display = 'none'
document.querySelector("#items").style.display = ''

Appending an element

// jQuery version
$("#items").append("<a href="" id="item5">Item 5</a>")

// Javascript version
node = document.createRange().createContextualFragment("<a href="" id="item5">Item 5</a>")
document.querySelector("#items").appendChild(node)

Retrieving Attributes and Data Attributes

// jQuery version
$("element").attr("attribute")
$("element").data("id")

// Javascript version
document.querySelector("element").getAttribute("attribute")
JSON.parse(document.querySelector("element").getAttribute("data-id"))
// or
JSON.parse(document.querySelector("element").dataset.id)

AJAX requests

// jQuery version
$.ajax({
url: "/items.json",
type: "GET",
success: function(data) {
console.log(data)
}
})

// Javascript version (with Rails UJS)
// This automatically includes your CSRF token for non-GET requests as well
Rails.ajax({
url: "/items.json",
type: "GET",
success: function(data) {
console.log(data)
}
})

Document Event Handlers

// jQuery version
$(document).on("turbolinks:load", function() {
// initialize code
})

// Javascript version
document.addEventListener("turbolinks:load", function() {
// initialize code
})

// Javascript version (with Rails UJS)
// This automatically includes your CSRF token for non-GET requests as well
Rails.ajax({
url: "/items.json",
type: "GET",
success: function(data) {
console.log(data)
}
})

In conclusion

The native functions of JavaScript are very powerful, since they run at a level lower than the one of JavaScript and that gives them greater speed when analyzing the nodes of a web and select them in the correct way.

So it’s easy to say that to a large extent Rails looks to be a faster framework.

About 4Geeks

Founded in 2016 by Allan Porras, 4Geeks is a global software engineering and data-driven growth marketing firm, focused on 10x ROI for Fortune 500, Global 2000 and fast-growing SMB around the world. 4Geeks serves in multiples industries including eCommerce, Retail, Healthtech, Banking & Fintech, Startups & B2B SaaS, Marketing and Real Estate.

Weekly Business Newsletter

Geek Waffle

Actionable Startups Tips from 4Geeks

Get free advice to build, grow and scale a profitable tech-based business.
Read by over 3000 CEOs and startup founders, weekly.