Cash is an absurdly small jQuery alternative weighing only 16 KB minified, and 6 KB gzipped.
It has all the common jQuery functionality you are used to, and it is relatively easy to migrate your project to it.
Getting started.
The easiest way to migrate to Cash is to include a script from a CDN, i.e.
<script src="https://cdnjs.cloudflare.com/ajax/libs/cash/8.1.1/cash.min.js"></script>
After that, continue using $
as if it would be jQuery:
$(function () {
$('html').addClass ( 'cash' );
$('a').on('click', function() {
console.log('All links disabled!');
return false;
});
});
Using Cash with a bundler.
When using a bundler like Webpack or Rollup, you can import Cash from a cash-dom package. For example,
import $ from 'cash-dom';
$(function() {
$('#root').html('<h1>Cash 💰</h1>').css({
fontSize: 52,
textAlign: 'center'
});
});
Exposing jQuery object.
If a third-party script uses a jQuery
variable instead of $
, you can overwrite that too. Here’s a simple workaround:
window.jQuery = window.$;
Patching deprecated jQuery functions.
Let’s see how we can patch some of older jQuery functionality to be able to move to Cash without changing the other libraries.
$.bind and $.unbind
$.fn.bind = function(event, listener) {
this.on(event, listener);
};
$.fn.unbind = function(event, listener) {
this.off(event, listener);
};
Shorthand event listeners, i.e. $.click()
This will cover both cases: when a function is provided to attach a listener, or when click()
is called without parameters to trigger a click event.
$.fn.click = function(listener) {
if (typeof listener !== 'undefined') {
this.on('click', listener);
} else {
this.trigger('click');
}
};
$.ajax, $.get, $.post
The simplest way to patch $.ajax
is to replace it with fetch()
equivalents. You will need to adjust for different variants like pulling a simple URL, or parsing the options passed to $.ajax
. Something like this will give you an idea of how to parse the options and how to chain the calls:
$.ajax = function() {
let args = Array.from(arguments);
if (typeof args[0] === 'string') {
return fetch(args[0]);
}
if (typeof args[0] === 'object' && args[0].url) {
let method = args[0].method || 'GET';
return fetch(args[0].url, { method });
}
};
$.get = function(arg) {
let opts = {
method: 'GET'
};
if (typeof arg === 'string') {
opts.url = arg;
} else {
Object.assign(opts, arg);
}
return $.ajax(opts);
};
$.post = function(arg) {
let opts = {
method: 'POST'
};
if (typeof arg === 'string') {
opts.url = arg;
} else {
Object.assign(opts, arg);
}
return $.ajax(opts);
};
$.get('data.json').then((result) => {
console.log(result);
});
Resources
Cash on Github: https://github.com/fabiospampinato/cash
cash-dom on npm: https://www.npmjs.com/package/cash-dom
Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.