Modular Javascript library with functionality similar to jQuery - javascript

jQuery and similar libraries provide a number of useful APIs for DOM traversal and manipulation. Where your site as high number of repeat visitors, their use is easily justified as caching will offset any bandwidth cost to the end user.
In other cases visitors to the site might always be unique and thus the bandwidth penalty for these libraries can be too severe relative to the benefits for a development team.
Are there any libraries that provide this style of DOM interaction while allowing you to choose the parts relevant to your page.
For example,
jQuery('#myId').addClass('error');
and many other APIs in jQuery can be replicated in a few lines of code, thus avoiding ~50kB of downloads.
So the question is, does a library exist that contains these functions with little dependency on other aspects of the library or will I need to create them myself as necessary?
Are there mechanisms/tools available to break down existing libraries like jQuery into their minimal components?

As discussed here, if you use google as a host of the libraries, the user probably already has it cached before they ever get to your site.
This page shows you which libraries are supported. Currently:
jQuery
jQuery UI
Prototype
script.aculo.us
MooTools
Dojo
SWFObject New!
Yahoo! User Interface Library (YUI) New!
I'm all for rolling your own, but be sure you know all the bugs of all the browser versions if you don't use a library.
Not a bad idea, though. It would be nice if you could create a custom version of jQuery. I'd especially like one for iPhone's Mobile Safari and Adobe AIR that stripped out all the non-webkit stuff.

The production version of jQuery is 19k, same as a rather small image. Not a severe bandwidh penalty in my book!
Edit: ..and worth every k, too.

MooTools allows you to download only the pieces you want. So if all you want is enough for JSON AJAX requests, you've got it.
http://mootools.net/core

Check out Sly. Only 3kB.

Sorry guys I somehow lost the page in which one was asking about JS libraries conflicts solution.
I had the same problem but now I solved it after playing around with some JQuery scripts. I know it is a bit pain in * but lets do it step by step.
First of all let me tell you that in my project I am using two different libraries. I am using Lightwindow and JQuery. I couldn't make both of the libraries function properly BUT I came up with the following script. You have to use this script within each function that is meant to be using the JQuery functions:
//This line says, that dollar sign $ is belongs to the JQuery library.
jQuery(document).ready(function($) {
//Your source code goes here.
});
Lets use it in little bit detailed. In my scenario I am having a click button that suppose to call the following function:
function popups(message, heading, actionlink, linkName) {
//This is the LINE that tell the rest of the source code
//to recognize JQuery functions.
jQuery(document).ready(function($) {
// get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
// assign values to the overlay and dialog box
$('#dialog-overlay').css({height:maskHeight, width:maskWidth}).show();
$('#dialog-box1').show();
// display the message
$('#dialog-message-row').html(message);
$('#dialog-message-heading').html(heading);
$('#dialog-message-actionlink').html("<a onclick=function('x') class='button' id='delete'>"+linkName+"</a>");
});//CLOSE JQuery translator
}

Related

WordPress without jQuery - Is this possible?

Relatively new to WordPress development. I am creating a new custom theme from scratch and would really like to just write vanilla javaScript without slowing things down with all the bloat of jQuery. I was thinking I could just simply dequeue jQuery.
Would this break anything behind the scenes for WordPress to function or is there no dependency?
jQuery is unlikely to slow you down as it's simply a bunch of optimized DOM selectors/DOM methods/utility functions.
You should be able to proceed with Vanilla JS unless any plugin or library you are using depend on it.
Yes, in theory jQuery will add to the download, but not as much as you think. jQuery gets loaded once if you set cache properly, all following pageloadfs, jQuery gets laoded from cache. If you use a CDN like Google's, big chances that your visitor already has it cached because they loaded it on another page. The parts of jQuery which you don't use, don't activate, they're smart like that.
Also, jQuery fixes some cross browser behaviour which you don't need to worry about and it offers a lot of functionality makes things a whole lot simpler, allowing you to focus on more interesting stuff.
TL;DR: jQuery will save you a much time building code, with(imo) a very minor cost. I do recommend using native JS when relevant, e.g. when you want a href of a clicked anchor: this.href.
Another way is to use the WP-JSON API plugin (comes with WP since 3.7 i think) and build your WP-site as a SPA using React/Vue/Angular/Whatever.
If you choose to go that route you wont have any bloat caused by anything but yourself. Always test your code. I personally like Vue.js, proper open-source framework, works like a charm for WP-development
Check this link out: https://snipcart.com/blog/reactjs-wordpress-rest-api-example

Partial JQuery library, tailored for each project requirement?

The JQuery let's you do all that wonderful stuff, while taking care of browser difference and maintaining a smooth language.
But what if I don't need all of this ..
Maybe all what I need is just the ajax call (that what most of really want anyway) and I don't want to pay the cost 90+K library just for that feature alone "or with a couple of other features"
Is there a way to "extract" the options you mainly need from JQuery?!
Something similar to what modernizer are doing? See here: http://modernizr.com/download/
Don't get me wrong here, I'm still a "lazy dev" who wouldn't like to reinvent the wheel & care about different browsers compatibility etc. .. so I still want to use a library .. but just tailored for my needs.
RobG pointed out the existence of MyLibrary which have a builder to deliver what I "only" need. Checking it out & it looks very cool. will certainly try it.
You can get an unminified copy of the jQuery source and remove the methods you don't need. Just be careful with removing methods that AJAX might have dependencies on.
For those developers who aren't "lazy dev"s, getting examples of what you are trying to do from the source of any open source libraries and forming your own modules is a great way to go.
There are resources out there to get you to just snippets you need such as Micro.js and james padolsey's jquery source viewer.
Once you have build a nice set of modules and established what dependencies you have internally, you can create min files specific to a page or portion of a project and cutting out all of the extra weight you don't need
This is can be the answer to the question regarding how to extract jquery needed part(s)
http://projects.jga.me/jquery-builder/
it divides the library (v1.10.2) to
ajax, css, deprecated($.uaMatch, $.browser, $.sub), dimensions , effects , event-alias , offset & wrap.
But for the purpose of the question, which is not paying that much valuable kilobytes over the precious network... it turn out that, using this builder, cutting everything only reduce the filesize by only 30% ...
so :) practical solution (till the moment) remains the same 1- not using jquery (use your or another library) or 2- accept the price of those 90k

How to optimize javascript/jquery code to speed up it's performance?

On one of my web projects, I use a lot of javascript/jQuery code, which is pretty slow on browsers (Windows 7 x64), especially on IE.
I use 3 Ajax requests at the same time only on Home page.
On Search page, I also use ajax requests, which are fired on scroll event, on any 'search tag' (simple anchor tag) click event and etc. which in general is making data loading very slow.
I use jQuery plugins such as, Anythingslider, jquery coockies plugin, Raty (rating plugin), Tipsuy, jQuery coreUISelect, jScrollPane, mouse wheel and etc. All those 3rd party plugins I have minified and combined in jquery.plugins.js file, which is almost 80KB.
I select a lot of DOM elements with jQuery. For example I use the following code:
$("#element")
instead of:
document.getElementById('element');
I also have one big CSS file, which is more than 5 000 lines, because I have combined all 3rd party jQuery plugins's css files into one file, for caching and less HTTP requests.
Well, I wonder, what can I do to optimize my code for better performance and speeding up web page load?
What kind of tools can I use to debug and my JS code? I forgot to mention that, when I refresh page in Google Chrome or Firefox with firebug or Chrome native developer tools opened, the page in that case loads also very slow. Sometimes the Firefox is even crushed.
Will selecting of DOM elements with raw js give me a better and faster way to parse the document? Or should I leave, the jQuery selecting? Talk about is about 50 elements.
Should I separate and after that minify external plugins, such as Anythingslider? Or is it better when I have 'all in one' js file?
Is it better to also separate jQuery plugins's css code from main style.css? Because even hovering on element and affecting the :hover state from css file, is pretty slow.
Well guys, I'm really counting on you.
I've been googling all night to find answers on my questions and really hope to find it here.
Thanks.
1) minify it
2) all the browsers come with built in debugging tools
3) reduce access to the dom by storing references in variables, don't look up the same element twice
4) separate and use a well known cdn
5) separate just cos its easier to manage
More jQuery tips here : jquery-performance-rules and here : improve-your-jquery-25-excellent-tips.
Make sure all your static resources are cached with no disk lookup
This library is pretty cool
You can compare selector performance here: http://jsperf.com/
Just setup your HTML code, include jQuery lib and place each selector you want to compare as various test case.
Many of the jquery-performance-rules still apply,
Also have look at here jquery-proven-performance-tips-tricks
Since there are a lot of ways to improve code, especially with such big websites like yours, I think it will be more useful to just post the external links, since these are very nicely written and concise tutorials and tools. Here are some of them:
Yahoo's tutorial, one of the most complete tutorials I know
W3Schools' tutorial on using image sprites, especially useful when there are a lot of small images on the page
Tips on efficient jQuery usage
Firebug, Firefox plugin for debugging javascript, html, css
HTML validator, can be very useful to quickly find errors in markup
HTML compressor for minifying your HTML code (there are a lot of tools on the web for this purpose, it's just a matter of finding the best one)
CSS compressor, same as for HTML
I would also recommend IDE for building web applications/websites called JetBrains' PHPStorm. It is commercial software, but definitely worth every cent, since it gives hints and tips for improvement while typing.
Raw performance may not be your issue. If you notice poor performance on page load, see this article I wrote specifically about minimizing javascript execution on page initialization.
http://blog.lavoie.sl/2013/12/optimizing-page-loads-by-reducing-javascript.html

Ripping JQuery from unnecessary/unused pieces: is this possible?

Is it possible to ONLY use portions of JQuery, just like with JQuery UI: customize ones own build in an easy way?
What i mean is imagine you ONLY need JQuery library for a silly, tiny but handy tool on youw site, lets say the Dialog boxes.
Are there JQuery builts available specifically supporting portions of functionality, at a fraction of the current Javascript code sizes?
If you only need a tiny portion of jQuery on your site, chances are good you don't need jQuery. Have you considered a smaller library such as underscore or head.js? Is there something particular about jQuery that you need that can't either be handwritten or found in a smaller library?
The minified version of jQuery is 82kb, and for speed's sake can be hosted on google's CDN. Check out the CDN Hosted jQuery section of this page: http://docs.jquery.com/Downloading_jQuery
You need to think of it from the opposite angle. What you need is dead-code removal (i.e. remove things not used), not "include things that are used."
The only popular dead-code removal processor I know of is the Closure Compiler's Advanced Mode. Beware I am NOT talking about Simple Mode, which only does minification and not dead-code removal nor any other optimizations.
jQuery, unfortunately, is not (yet) compatible with the Closure Compiler's Advanced Mode.
However, you can consider the Dojo Toolkit, which is compatible with Advanced Mode after certain modifications. Read it here.
If you want to use a popular JavaScript library, but don't want to include everything, you can look into Dojo.
A Dojo application with only very light usage of the Core functions, after compiling with Advanced Mode, can be reduced to less than 40% of the size of a only-minified version (e.g. Closure Simple Mode).
Not that I know of. Except for css based selector which is sizzle incorporated into jQuery. But I am sure you can write or find pure js library that has only the functionality you need and skip jQuery if you really want to.
You can have at jQuery in pieces: https://github.com/mythz/jquip
It is unofficial, though.
You could feed jQuery plus all of your code through the Closure Compiler; that would remove everything you weren't actually using. I don't know how much smaller it would get, though; it might be all interdependent on the inside.

How to achieve library-agnosticism when building a javascript framework?

I've started looking into architecturing a javascript framework.
I don't want to reinvent the wheel here, especially regarding browser quirks, and know that for that matter, I'll have to rely, at some point, on some commonly-used libraries to handle low-level concerns.
The thing is, I'm not sure how i can depend on an external library for some piece of functionality (say for example dom manipulation), without tying it to my design.
Practical examples would help make a better point, but I'm not at the design stage yet, and I'm merely trying to avoid getting started on the wrong foot.
So I'm looking for some examples, guidelines, best-practices or maybe patterns that could help in this situation.
Any insight ?
EDIT : Bit of a clarification on why I'd want to do this.
My goal is to build something resembling more of an application framework than most traditional libraries like jQuery.
Think layered architecture, where the libraries would fit into the infrastructure layer (as per Evans' definition in Domain Driven Design), and handle things such as events, dom traversing and manipulation etc...
This is a very broad question, but if I were you, I would use jQuery as a base. It is a very easy library to extend and add functionality too.
I'd recommend grabbing a copy of ExtJS and taking a look at how they provide support for replacing the underlying core of their product. You can use their higher level libraries, such as grids, trees, etc, but choose to use YUI or prototype in place of their Ext core.
That should give you a good starting point.
Edit to answer comment:
Once you've downloaded ExtJS, take a look in the "adapter" folder. In there, you'll see the various adapters that exist to make ExtJS work with other libraries. You'll quickly see how they define functions that in turn make use of the appropriate underlying lib.
Segregate your code:
use the external libraries to the fullest possible, within their separate section of code.
Taking jQuery as an example, just designate a section for interfacing with jQuery and then use jQuery within that section of the library like there's no tomorrow, and give it interface functions that the rest of the code uses exclusively.
Frankly, if you integrate a library with your code and try to make it generic enough that you can trivially swap it out with something else, you're probably going to neuter the library to the point where you might as well have not included it at all.
Accept that you may need to rewrite if you end up swapping libraries, but prepare for that by giving the library-interfacing code it's own separate section, and you'll be able to write less generic, more powerful code with those external libraries and save yourself a lot of work.
This doesn't answer your pattern question, but a word about the frameworks. All of the modern JavaScript libraries are pretty good at playing well with each other, but some are better than others. Just make sure that they libraries don't monkey-patch the core objects with arbitrary properties or muck with the global namespace and you should be good to go. JQuery and YUI are both well designed and namespaced libraries. Dojo is also quite good, but a couple years ago when looking at all of the options, it seemed like Dojo encouraged the use of proprietary element attributes in markup as JS hooks. At that time Prototype was the library that mucked with objects like String/Array and didn't play well with others. I haven't looked/used Dojo or Prototype so take that with a grain of salt. I'm actively using YUI and JQuery in the same app; YUI for widgets and event management and JQuery for Selector/DOM manipulation.
I'd suggest you pick a single general purpose library or no library at all, depending on the requirements of the framework you plan to write. It's very difficult to make any kind of recommendation without more information, such as what your framework is aiming to achieve, who will be using it and in what kind of environment.
If you're considering writing a script of reasonable complexity then I would suggest learning the relevant "low level" DOM manipulation techniques for yourself. It's not as difficult as devotees of some of the famous general purpose libraries would have you believe.
Use some kind of interface to link to the library.
Don't do:
$("blah").something();
do
something("blah")
function something(id){
$(id).something();
}
Since you could call something() 20 times, it'll be simpler to update if the actual use of the library is in only 1 place.
It'll add development time and then complexity, but you won't be as dependent on a library.
I don't think this can be achieved very effortlessly. If you really want this behavior, I think you'd have to manually map the features that are covered by all libraries you want to include support for.
So that the implementation would look like:
yourLibrary.coreFramework = 'prototype';
yourLibrary.doStuff();
And your librar would treat it in the following manner:
function doStuff() {
var elem = getElement('id');
// do stuff with 'elem';
}
function getElement(id) {
switch(this.coreFramework) {
case 'prototype': return $(id);
case 'jquery': return $('#'+id);
/* etc */
}
}
Check out the jQuery or prototype frameworks.
If you decide you need to, then extend these.

Categories

Resources