How can I reduce jQuery? – Code Utility

[

I’m using just a few basic jQuery functions on my site.
How can I remove unused jQuery code?
Knowing only the basics, I looked at the code and was not sure where to start.
If you could point me in the right direction, that would be appreciated.

Thanks.

,

jQuery itself isn’t really built to be selectively used. There are lots of interdependencies between its own functions and the source isn’t laid out to be easy to modularise. Unlike the situation with plugins like jQuery-UI, the core of jQuery is pretty much take-it-or-leave-it.

If you’ve only used a few simple functions, you might be able to rewrite them in plain JavaScript. If the main function you’re using is selectors you can use Sizzle, which is the underlying selector library that jQuery itself uses. Otherwise… not really.

,

If you want to further reduce the code size, minify and gzip or deflate it. Beware that gzipped code needs to be uncompressed before it’s executed, thus causing a delay. The jQuery download page offers an already minified and gzipped version.

Another option you could look into is using CND hosted jQuery, that is jQuery hosted by third party organizations such as Google or Microsoft. Details in the jQuery download page.

,

The question is – why? Production version of jQuery 1.4.2 is only 24Kb. With proper cache control of the file, it will be downloaded only once and cached. Why bother?

,

As others have mentioned, you don’t need to do this.

If you’re concerned about bandwidth, you can reference jQuery from Google’s AJAX API, like this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.js"></script>

To answer the question, that would be extremely difficult.

As you’ve noticed, jQuery is written in a very terse and efficient manner, and does not have easily removable chunks.

,

Beyond the tips to minify/compress/CDN-host your Javascript, which you should do for any Javascript library, have a look at Zepto, which aims to be a slimmer jQuery-alternative designed for the mobile browser. It’s not a drop-in replacement for jQuery, but supports all the important things like selectors, AJAX operations, and utilities. I wrote a brief blog post on the subject: http://blog.straylightrun.net/2012/10/23/so-you-want-to-use-jquery-in-your-javascriptwidget/

,

You can create your own version by following the documentation in the official jQuery repository here: https://github.com/jquery/jquery#how-to-build-your-own-jquery, but it involves using Grunt.

If you are using Webpack you can follow the steps here: https://gist.github.com/rhaglennydd/abb2d27144e1a595e7c850b0a7611a21.

I think that a link only answer breaks some of the rules in SO, so I’m giving a short description.

1. Install jQuery throught npm

npm install jquery

2. Copy the exported code

Copy the code from node_modules/jquery/src/jquery.js to a file in your project (ex. code/resources/js/jquery)

3. Edit the path to source files

The imported files must be the original files in the node_modules folder.
For example './core', can become '../../../node_modules/jquery/src/core'.

4. Remove the modules that you don’t need

Remove or comment some modules: be sure to test that your code keeps working without raising errors.

5. Add your custom jQuery as an alias in the Webpack configuration

This will tell Webpack to use your version whenever jquery is needed in your code or in one of your dependencies.
For example:

module.exports = {
  resolve: {
    alias: {
      jquery: `${environment.paths.source}/js/jquery-custom/jquery-custom.js`,
    }
  }
};

Final word

I have seen that if I remove a lot of modules the size will reduce, but if you don’t it can even slightly increase: so this is a good strategy if you need to progressively remove some code or if you already use very little modules, otherwise you’d better stick to the original or find an alternative library.

,

It’s an old question but still relevant topic….

I concocted this (please note that it’s only a draft that can be used as a starting point)

$ = function () { 
    if ( arguments[0] !== undefined ) {
        stubelement = arguments[0] ;
        if ( typeof stubelement == "string" ) {
            switch ( true ) {                   
                case stubelement == 'body' : return document.querySelector(stubelement); break;
                case stubelement == 'html' : return document.querySelector(stubelement); break;
                case stubelement.charAt(0) == ',' : if( document.querySelectorAll(stubelement.replace(',','.')).length > 0 ) { return document.querySelectorAll(stubelement.replace(',','.'))[0]; } break;
                case stubelement.charAt(0) == '.' : if( document.querySelectorAll(stubelement).length > 0 ) { return Array.from(document.querySelectorAll(stubelement)); } break;
                case stubelement.charAt(0) == '#' : if( document.querySelectorAll(stubelement).length > 0 ) { return document.querySelectorAll(stubelement)[0]; } break;
                default :   if( document.querySelectorAll(stubelement).length > 0 ) { return document.querySelectorAll(stubelement)[0]; } break;
            }
        } else { return arguments[0]; }
    } 
    return document.querySelectorAll("#emptyelement")[0];
}

function stubappento () { if ( (arguments[0] !== undefined) && (arguments[1] !== undefined) ) { $(arguments[1]).append($(arguments[0]).outerhtml()); $(arguments[0]).remove(); } }
function stubprepento () { if ( (arguments[0] !== undefined) && (arguments[1] !== undefined) ) { $(arguments[1]).prepend($(arguments[0]).outerhtml()); $(arguments[0]).remove(); } }

HTMLElement.prototype.val = function () { if ( arguments[0] !== undefined ) { this.value = arguments[0]; } else { return this.value; } };
HTMLElement.prototype.html = function () { if ( arguments[0] !== undefined ) { setInnerHTML(this,arguments[0]); } else { return this.innerHTML; } };
HTMLElement.prototype.append = function () { if ( arguments[0] !== undefined ) { setInnerHTML(this,(this.innerHTML + arguments[0])); } else { setInnerHTML(this,(this.innerHTML + ' ')); } };
HTMLElement.prototype.prepend = function () { if ( arguments[0] !== undefined ) { setInnerHTML(this,(arguments[0] + this.innerHTML)); } else { setInnerHTML(this,(' ' + this.innerHTML)); } };
HTMLElement.prototype.outerhtml = function () { if ( arguments[0] !== undefined ) { this.outerHTML = arguments[0]; } else { return this.outerHTML; } };

HTMLElement.prototype.attr = function () { if ( arguments[1] !== undefined ) { this.setAttribute(arguments[0],arguments[1]); } else { return this.getAttribute(arguments[0]); } };
HTMLElement.prototype.data = function () { return this.getAttribute('data-' + arguments[0]); };

HTMLElement.prototype.css = function () { 
    if ( typeof arguments[0] == 'object' ) { for ([csskey, cssvalue] of Object.entries(arguments[0])) { this.style[csskey] = cssvalue; } } 
    else { if ( arguments[1] !== undefined ) { this.style[arguments[0]] = arguments[1]; } else { return this.currentStyle ? this.currentStyle[name] : window.getComputedStyle ? window.getComputedStyle(this, null).getPropertyValue(arguments[0]) : null; } }
};

HTMLElement.prototype.remove = function () { this.parentNode.removeChild(this); };
HTMLElement.prototype.hide = function () { this.style.display = 'none'; };
HTMLElement.prototype.show = function () { this.style.display = 'inline-block'; };
HTMLElement.prototype.showblock = function () { this.style.display = 'block'; };
HTMLElement.prototype.toggle = function () { 
    stubtoggle = this.getAttribute('data-stubtoggle');
    if ( stubtoggle === null ) {
        displa = this.style.display; 
        if ( this.classList.contains("inlineBlock") ) { displa = 'inline-block'; }
        log("null-->>"+displa);
        switch (displa) {
            case 'block' : displa = 'blocksee'; break;
            case 'inline-block' : displa = 'inlinesee'; break;
            case 'none' : displa = 'inlineunsee'; break;
            default : displa = 'blocksee'; break;
        }
    } else {
        displa = this.data('stubtoggle'); log("set-->>"+displa);
    }
    switch ( displa) { 
        case 'blockunsee' : this.setAttribute('data-stubtoggle','blocksee'); this.showblock(); break;
        case 'blocksee' : this.setAttribute('data-stubtoggle','blockunsee'); this.hide(); break;
        case 'inlineunsee' : this.setAttribute('data-stubtoggle','inlinesee'); this.show(); break;
        case 'inlinesee' : this.setAttribute('data-stubtoggle','inlineunsee'); this.hide(); break;
    }
};

HTMLElement.prototype.length = function () { return this.innerHTML.length; };
HTMLElement.prototype.width = function () { return this.getBoundingClientRect().width; };
HTMLElement.prototype.height = function () { return this.getBoundingClientRect().height; };
    
HTMLElement.prototype.addClass = function () { this.classList.add(arguments[0]); };
HTMLElement.prototype.removeClass = function () { this.classList.remove(arguments[0]); };

HTMLElement.prototype.disable = function () { this.disabled = true; };
HTMLElement.prototype.change = function () { this.dispatchEvent(new Event('change')); };
HTMLElement.prototype.stubtrigger = function () { this.dispatchEvent(new Event(arguments[0])); };
HTMLElement.prototype.on = function () { this.addEventListener(arguments[0],arguments[1]); };
HTMLElement.prototype.off = function () { this.removeEventListener(arguments[0],arguments[1]); };

Array.prototype.count = function () { return this.length; };
Array.prototype.hide = function () { this.forEach(function(a){a.hide();}); };
Array.prototype.show = function () { this.forEach(function(a){a.show();}); };
Array.prototype.remove = function () { this.forEach(function(a){a.remove();}); };

and the usage is really similar to jquery

$().html();
$().html("new content");
$().append("new content");
$().prepend("new content");

$("#tomove").appendTo("#newid");   ===>>> stubappento(',ap','#message2');

$().val();
$().val("new val");

$().hide();
$().show();
$().remove();                               
$().toggle();

// for slideToggle simply add style=”transition:height 1s;” to the desired divs or add is a class in your .css .transitheight1{transition:height 1s;}

$().attr("a");
$().attr("src","new src");

$().each ===>>>     $('.bees').forEach(function(a,b){a.hide();});

$().css
$().width
$().height

$().addClass
$().removeClass

$().on("focus",function(){});

$().oninput() ====>>>>>> onclick="$(this).on('input',function(){});"

$().focus()
$().change()
$().click()

$().keyup(function(event) {}); ====>>> window.onkeyup = funcname; —— https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event
$().keydown(function(event) {}); ====>>> window.onkeydown = funcname; 

$().prop("disabled", true); ====>>>>>> $('#id').disable()

$().length ••••••••••••••••••••••••••>>>>>>      $('#ap4ee')?.length()

$()[0].play(); OR .get[0].play =====>>>> $('#audio').play();
$()[0].pause(); =====>>>> $('#audio').pause();

]