Javascript dead code elimination - javascript

I'm looking for a way to reduce a javascript library/framework with the objective of only sending to the client (browser) only the necessary code. I've searched and I found that, for example, closure compiler can't remove jquery dead code.
How can I write a web application, using javascript or any other languages/frameworks/tools to archive this goal? I've nothing against frameworks but in mobile devices performance counts a lot. I've tested HTML5 mobile apps on cheap android devices and it's terrible to use due to performance issues. I want to extract maximum performance.

My 2 cents:
In term of performance, use good practises with a linter such as jslint, jshint, or eslint.
To check wich concept is better than another one, you can check at jsperf or make your own ones with benchmark.js.
For loading time, jQuery is a bit big for mobile. Zepto is a good alternative. Imo, it's better to concat all js files on mobile than async load the js.
MicroJs is a site which list all libraries that usually fit a specific need.

Related

Tools for JS and CSS file concatenating

I recently started working with a large code base with many (15-20) js requests per page. I'm tasked with optimization and performance improvement of these sites.
I've been using tools like Google's PageSpeed and Yahoo's YSlow in conjunction with WebPageTest.org's tests to determine a baseline speed of the site and area of improvement. I'm curious if there are some standard or best-practice solutions for concatenation and minification of JS and CSS files.
I watched: http://www.youtube.com/watch?v=30_AIEhar-I and the first 20 minutes were really good at hammering mod_pagespeed as a good target.
I'm currently considering mod_pagespeed with a YUI compressor and perhaps a sprite generator on top of it all.
What are some good tools that I may have missed or things that I should be concerned about with my current build?
Edit: It should be noted that this is one page of many (possibly hundreds) and the site receives a new build every two weeks so being able to automate this concatenation and minification is a must, I can't just do it once and call it good.
Edit 7/30/2012 -
I spent some time looking at different tools, it's hard to say which ones are the best but at this time, not very many people use mod_page speed.
Closure is more widely used for certain, but even that is lacking. It seems the optimal way to do this is to just use a plugin with YUI.
There are other places that suggest Packer but it seems that many believe the smaller file sizes are eliminated by the necessity to unpack them on the client machine. This stackoverflow response is a good read regarding these types of tools.
Google's Closure Compiler is quite nice for concatenating and minifying JavaScript. It has the added bonus of linting your code for you when you compile, it will remove dead code, and it can also perform compile-time type checking if you include type hints in docblocks.
In certain cases, the dead code removal feature gives Closure a huge advantage over other minifiers... for example, think of cases where you include a library, but only use about 10% of the functionality. The other 90% can be removed if you compress the library along with the rest of the project.
As for CSS, YUI compressor is probably your best bet if you want something fancy. Otherwise, you could just concatenate the files together using cat and take the hit of a few extra bytes from whitespace.

Is there a jQuery alternative for building faster web sites

We are about to commence a redesign of our site and are exploring all options in improving performance. The site is fairly heavy in javascript loaded adverts, therefore we need to be really lean with the javascript we use.
Do any of you have any experience of lighter frameworks or more efficient frameworks that I could explore? Or any resources that you could point me toward? YUI looks like an interesting concept … has the loader being tested in anger? ANy good?
Any thoughts would be appreciated.
Cheers.
edit: Sorry, I wasn't clear. The sites performance currently is pretty good, we are not redesigning due to performance issues, it is due to a rebrand. We just wanted to take the opportunity to review best practices.
jQuery 1.4.2 is lean and mean. You'll be hard pressed finding something faster or more lightweight.
As an example, here is a framework test called slickspeed from mootools. It tests a framework's ability at finding elements in the DOM. The version of jQuery being tested is 1.2.6. Depending on your browser, jQuery performs exceptionally well. In my Chrome browser, jQuery beat all the others with a total time of 20 milliseconds.
And since version 1.2, jQuery has had astounding improvements in optimization and speed, especially with 1.4.
That said, a framework isn't going to make you code better. You can write some seriously slow scripts using any framework, including jQuery.
If, however, you write optimized code, jQuery can be so fast you don't even notice.
Pointy's comment above is spot on. All these guys do all day is worry about how to perform better. So it's pretty optimized.
addendum
This is from jQuery's blog:
While comprehensive benchmarks like Taskspeed can be interesting if deconstructed into individual sub-tests for further study, as a project we tend to stay away from using them as an accurate measure of true, overall, library performance. Considering how many aspects make up a library, not to mention the different techniques that they offer, cumulative results rarely reflect how an actual user may use a library.
So take that as you will.
I prefer YUI3 for larger apps and just about anywhere that 'load on demand' can offer benefits :)
I agree that slowdowns mostly stem from how you implement your app, which is one of the benefits, imho, of YUI, it lends itself naturally towards more modular implementations.
Using the yui loader to bring in page elements widget style allows for good code reuse (and caching) as well letting the user see 'something' quicker.
It won't really solve your JS ad issues though, for that, the best thing you can do is load it as near the bottom of the page as possible, and perhaps look at what loading options the adservers have.
Re: Stephen's comment
Well, raw speed for tight loops are sometimes meaningful, sometimes not. There is also the issue of the implementations used for the comparison, the YUI3 code posted in Ejohns version looks positively gimped compared to the jQuery code, look fx at the first one. Where jQuery adds almost the complete DOM element from a string while YUI3 is going thru all kinds of hoops, relatively speaking.
For a version that is written by someone who knows YUI3 have a look at http://yuilibrary.com/~msweeney/yui-tests/taskspeed/ the newest jquery isn't represented, but it does have YUI3 as ~4 times faster overall than jquery 1.3.2 in my Chrome.
Update
http://www.yuiblog.com/blog/2010/10/27/jquery-and-yui-3-a-tale-of-two-javascript-libraries/ a jquery users experience of yui3.
Probably the best place to start off is not to ask what frameworks can help but why your current site has bad performance. I would start off with tools like Yahoo's YSlow and also Dynatrace ajax edition. Dynatrace is nice because it will point out javascript/dom manip stuff that make your pages slow. You will want to use more than just two performance tools though since they all pretty much have their own idea's on what makes a page fast. Once you have that down then I would come into a forum and state that your having performance issues with X and what can I do to fix.
vapor.js is the world's smallest and fastest javascript library
http://vaporjs.com/
I think you should have a look at zepto.js
http://zeptojs.com/
this article gives you some advices for porting your jquery code
http://blog.pamelafox.org/2012/03/porting-jquery-plugins-to-zepto-tips.html
jQuery is plenty lightweight if coded properly. It sounds like which framework you are using is not the problem, but either a) why the javascript your writing is performing slowly, or b) why you are using so many slow loading ads to begin with.
But if you really want to look into other frameworks, here's a handy comparison chart: Comparison of JavaScript Frameworks
I just wrote an internal app for our company using jquery and jquery UI (http://jqueryui.com/), mixed in with c#. I found it to be extremely lean and fast - no problems whatsoever.
the jquery ui makes it easy to theme the website...
and by adding other components like blockui, jgrowl, etc you should be able to do anything you want!
Sprint is a tiny, fast alternative.
Check out the repo for benchmarks on a few functions, compared with recent versions of jQuery and Zepto.

What are the arguments against using a JavaScript Framework for a Web site development company? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Our company builds websites and web applications. We are a small firm and our team of developers are always building the javascript functions from scratch or copying from other websites built by us. Every time I bring to the table the word standardization and using a JS framework like JQuery, Prototype or any other, I am told Frameworks have the three points below as arguments against them:
Mainly for people that don't know enough JS
Frameworks limit Javascript developers
Frameworks bloat the actual development code with a lot of things that are not used.
We don't use enough Javascript in our applications for us to need JS framework
In my mind it seems that Frameworks, give our team a good starting point, documentation, a community and always the option to grow on top of the framework. Could some Framework users elaborate further?
EDIT 1:
Thanks to all of you for your great responses. I really did not think that this was going to be such a hot topic. I am glad I asked the question. I posted another similar question in the following link in case you might think you want to add something. The topic of the new question is CSS related. Thanks.
By your coworkers point of view, .NET and JAVA are for people who don't know enough assembly.
Frameworks exist for a reason. They allow you go focus on the problem instead of dealing with repetitive code. They allow you to be confident (assuming you use well tested frameworks) that certain pieces of your code are reliable and well tested.
If your coworkers are against frameworks, I would seriously consider moving on.
Since no one has mentioned it - a Javascript framework rapidly becomes one more project dependancy, and in general terms, dependencies are bad as they represent points of failure.
As for this:
Mainly for people that don't know
enough JS
Without elaborating, I will say that if one of our team said something like that in my presence, I would try to shrug it off as a joke. If I thought they were being serious, I would probably have to kill them.
And as for this:
Frameworks limit Javascript
developers
That could translate to "Frameworks make it marginally harder to write spaghetti code, and that's what I do best"
Those are not arguments, they are excuses.
Arguments against:
Frameworks prevent you from re-inventing the wheel
Frameworks generally contain well tested code
Frameworks are well supported by the community
Frameworks force you to focus on the business problem you're trying to solve
</sarcasm>
Frameworks may have a license you don't agree/can't work with
A few positives for javascript frameworks (like JQuery).
They provide standardization in ui
elements.
Reduce time to develop complex
interfaces and effects.
Normalize efforts by providing
functions that are already
cross-browser compatible.
Due to efforts in cross
compatibility documentation is more
useful in a framework as you can use
the framework's api as canon
instead of searching for obscure
support for various/proprietary
javascript functions.
Reduced learning curve for new
developers making them productive on
your software quicker.
I completely disagree that a framework limits javascript developers. Quite the opposite actually. Most frameworks provide extensive plug-in mechanisms where the framework can be extended using raw javascript utilizing hooks in the framework itself.
I'll use jQuery as an example, but what I'm saying here could apply to most JavaScript frameworks.
Many frameworks (notably jQuery) are far too monolithic and not modular enough.
While depending on well-tested 3rd party software is often more than justified, "frameworks" tend to give you a lot more functionality than you need at the moment.
In many projects, I very much like the convenience that jQuery gives me for selecting sets of elements (using $(".classname"), for example). But, if I'm not using any significant amount of AJAX, I don't need the AJAX utilities provided by jQuery.
Software should do one thing and do it well, and software written in JavaScript is no exception. Most of the frameworks you refer to try to do everything, resulting in unnecessary complexity.
One place this can bite you is when you're considering upgrading to the next version of the framework. That involves crawling through jQuery's changelogs for backwards-incompatible changes and searching your project for areas where that code is used. This can be quite a nightmare, especially if you don't necessarily have a comprehensive list of which jQuery features you use and which ones you don't.
Also, jQuery (and other frameworks) tends to cause developers to start depending on new features of jQuery without even thinking about it, making it harder to determine which features of jQuery your project uses and which it doesn't.
If you use a utility which does one thing, then you know exactly which features of that utility you're using. There's only one. (If you aren't using that utility at all, it's easy to determine. Such a determination would mean you could safely remove it from your project.)
I'm all for using well-tested 3rd party code. But if it tries to do too much, (that is, if it's a framework rather than a utility), you should probably look for an alternative. If it tries to do too much (like jQuery tries to do too much), then it's got some serious, foundational design flaws that will probably come back to bite you.
I'm surprised no one has already mentioned it:
A lot of web developers default to using JQuery without considering the alternatives
And end up including it on a web page to do a few trivial tasks which could easily be done in pure JavaScript
The result is that users have to wait for the whole library to download and it slows down web browsing
Also:
Some web developers get carried away with the design of web pages, and end up developing unnecessarily complex web pages because of the power of JQuery
Just because JQuery enables you to create scripts with good cross-browser compatibility it doesn't mean that the end result is usable on different devices / interfaces
I'd also argue the cross-browser compatibilty because I've seen instances of webkit not playing well with JQuery
JQuery encourages "fast" scripting - but if you rush it you are likely to have missed something out
Writing in JavaScript from scratch is slower - but I believe that you end up with a more complete solution which more closely matches the users needs
Using JQuery can shift the focus of the web developer to creating web sites which are highly graphical and visually appealing, whereas the focus should be on functionality and usability
JQuery is not a silver bullet for web development
I am biased here because I don't use JQuery, but it is because I haven't found a need for it yet - maybe it's because I focus more on usability and functionality rather than making the user interface look pretty (sorry I know JQuery can do more than that).
An argument against libraries is BROWSER SUPPORT most libraries support only a subset of browsers out there .
Here is an example of BBC rolling out their own instead of using something like jquery .
I liked the answer of pb +
Mainly for people that don't know
enough JS
I believe it is too complicated for them, so they use this excuse. FW allows you to build much more complex applications.
Frameworks limit Javascript developers
bullshit
Frameworks bloat the actual
development code with a lot of things
that are not used.
what is it today extra 100k-200k? especially if you use the CDN versions (at google for instance). And this is assuming you use nothing in the FW.
There are plenty of good reasons to be suspicious of frameworks in general, balanced of course by lots of reasons why they are worthwhile.
I use jquery now, and frankly within an hour of learning it realised that it fits the job so well that if it didn't exist I'd only end up reimplementing something very similar myself, only it wouldn't be as good or as cross platform.
There isn't much bloat there, it's very small and well designed and does nothing at all that stops you writing any javascript you want for specific cases that don't fit your needs.

Which JavaScript framework is generally used for high performance websites?

There are different JavaScript frameworks like jQuery, Dojo, mooTools, Google Web Toolkit(GWT), YUI, etc.
Which one from this is suitable for high performance websites?
(Full disclaimer: I am a Dojo developer and this is my unofficial perspective).
All major libraries can be used in high load scenarios. There are several things to consider:
Initial load
The initial load affects your response time: from requesting a web page to being responsive and in working mode. Trivial things to do are:
concatenate several JavaScript files together (works for CSS files too)
minimize and/or compress your JavaScript
The idea is to send less — good for the server, and good for the client.
The less trivial thing to do:
structure your program in such a way so it is operational without all modules loaded
Example of the latter: divide your modules into essential (e.g., the core logic), and non-essential (e.g., helpers: tooltips, hints, verifiers, help facilities, various "gradual enhancers", and so on). The idea is that frequently there are things which are not important for frequent users, but nice for casual users ⇒ they can be delayed.
We can load essential modules first and load the rest asynchronously. Example: if user wants to edit an object we need to show it first, after that we have several hundred milliseconds to load the rest: lookup tables, hints, and so on.
Obviously it helps when asynchronous loading of modules is supported by the framework you use. Dojo has this facility built-in.
Distribute files
Everybody knows that due to browser restrictions on number of parallel downloads from the same site it is beneficial to load resources (images, CSS, JavaScript) from different domains:
we can download more in parallel, if user's line has enough bandwidth — these days it is almost always true
we can set up web servers optimized for serving static files: huge disk cache, small workers, keep-alive, async serving, and so on
we can remove all unnecessary features we don't need when serving static files: sessions, cookies, and so on
One frequently overlooked optimization in JavaScript applications is to use CDN:
your web site can benefit from the geographical distribution of CDN (files can be served from the closest/fastest server)
user may have required files in her cache, if they were used by other application
intermediate/corporate caches increase the probability that required files are already cached
the last but not least: these are files that you don't serve — think about it
Again, Dojo supports CDNs for a long time and distributed publicly by AOL CDN and Google CDN. The latter carries practically all popular JavaScript toolkits too. Obviously you can create your own CDN and your very own CDN- and app- specific Dojo build, if you feel you need it — it is trivial and well documented.
Communication bandwidth
How that can be different for different toolkits? XHR is XHR.
You need to reduce the load on your servers as much as possible. Analyze all traffic and consider how much static/immutable stuff is sent over the pipe. For example, typically a lot of HTML is redundant across several pages: a header, a footer, a menu, and so on. Do you really need all of these to be sent over every time?
One obvious solution is to move from static HTML + "gradual enhancements" with JavaScript to real "one page" JavaScript applications. Again, this is a frequently overlooked, but the most rewarding optimization.
While the idea sounds easy, in reality it is not as simple as it seems. As soon as we go from one-liners to apps we have a plethora of questions, and the biggest of them is the packaging: what your components are, what components are provided by the toolkit, and how to package and deliver them.
Dojo provides modules, good OOP for general classes, widgets (a combination of an optional HTML and related behaviors), and a lot of facilities to work with them. You can:
load modules on demand rather than in the head
load modules asynchronously
find all dependencies between modules automatically and create a "build" — one file in simple cases, or more, if your app is big and requires several layers
while doing the "build" it can inline all HTML snippets for your widgets, optimize CSS, and minify/compress JavaScript
Dojo can automatically find and instantiate widgets in HTML saving a lot of boilerplate code
and much much more
All these features help greatly when building applications on the client side. That's why I like Dojo.
Obviously there are more ways to optimize high load web sites but according to my practice these are the most specific for JavaScript frameworks.
Quite simply: all of them.
All frameworks have been built in order to provide the fastest performance possible and provide the developers with useful functions and tools. Your choice should be based on your requirements.
JavaScript runs on the client-side, so none will affect your server performance. The only difference server-side is the amount of bandwidth used to transfer the .js files to the client.
I'm personally fond of MooTools because it answers my requirements and also sticks to my coding ideals. A lot of people adopted jQuery (I personally don't like it, doesn't mean it's not great). I haven't used the other ones.
But none is better than the other, it's all a question of requirements and personal preference.
I do not really think it makes a bit of difference. The big ones seem to use a mixture of Jquery & prototype along with others.
Quite frankly, it makes no difference what you use for heavily visited websites as we are talking about client technologies. After the file is loaded, there are not really any overheads. So, if you just want to do one simple thing and multiple frameworks support it, use whatever one has the smaller file size (of course, if it performs really bad, use another!)
This being said, google hosts a lot of the frameworks, so even this is really a non issue. I use Jquery hosted by Google and am very happy.
http://code.google.com/apis/ajaxlibs/
Backend and what the server should be using is a whole different question where you will get a thousand different answers!
I'd recommend you look into Dojo.
Dojo 1.6 is also the first (and only) popular JavaScript Library that can be successfully used with the Closure Compiler's Advanced mode, with the massive size, performance and obfuscation benefits attached to it -- other than Google's own Closure Library, that is.
http://dojo-toolkit.33424.n3.nabble.com/file/n2636749/Using_the_Dojo_Toolkit_with_the_Closure_Compiler.pdf?by-user=t
In other words, a program using Dojo can be 100% obfuscated -- even the library itself.
Compiled code has exactly the same behavior as plain-text code, except that it is much smaller (average 25% over minifiers), runs much faster (especially on mobile devices), and almost impossible to reverse-engineer, even after passing through a beautifier, because the entire code base (including the library) is obfuscated.
Code that is only "minified" (e.g. YUI compressor, Uglify) can be easily reverse-engineered after passing through a beautifier.
Well - as an example stackoverflow relies on jQuery ( and uses the google apis link ) - it's one of the speediest and most popular libraries and not only that but I'd say it's the easiest to use. What type of behavior are you going to have on the site? It really all depends on your needs.
The answer, as always, is: it depends. What kind of performance are you talking about? Download speed? Use a minimiser and there's probably not a lot of difference. Or client-side performance, and what are you doing with it?
But, I would suggest that if you're after raw performance, I would not use a framework at all, and create low level javascript that will be far more difficult to maintain.
Some good information can be found on the YUI site.
As other answers already explained, the framework's not going to be the bottleneck in your site's performance -- rather, many other factors are. If you use popular frameworks and load them from popular URLs for them (e.g. AOL's or Google's) they're likely to be cached in your users' browsers, so you don't have to worry much about that, either.
If you care at all about performance, however, absolutely DO check out Steve Souders; work -- including both of his books, "High Performance Web Sites" and "Even Faster Web Sites".
I'm biased, as Steve is a friend and a colleague (and we share publishers as well), but I praised and admired his work even before we met in person and became colleagues -- I'm mostly a back-end person, as he used to be, so I just can't help admire somebody who, coming from the same background, had the integrity and courage to switch almost entirely to front-end focus as he realized THAT was by far the bottleneck for user-perceived performance (i.e., somebody who had the gumption to put user experience first, something we all pay homage to, of course, but don't always practice, when that "overriding priority" gets in the way of our own professional specialties, interests and skills...).

Are GWT wrappers on top of javascript libraries discouraged?

I'm in a process of selecting an API for building a GWT application. The answer to the following questions will help me choose among a set of libraries.
Does a third-party code rewritten in
GWT run faster than a code using a
wrapped JavaScript library?
Will code using a wrapped library
have the same performance as a pure
GWT code if the underlying
JavaScript framework is well written
and tuned?
While JavaScript libraries get a lot of programming eyeballs and attention, GWT has the advantage of being able to doing some hideously not-human-readable things to the generated JavaScript code per browser for the sake of performance.
In theory, anything the GWT compiler does, the JavaScript writers should be able to do. But in practice the JS library writers have to maintain their code. Look at the jQuery code. It's obviously not optimized per browser. With some effort, I could take jQuery and target it for Safari only, saving a lot of code and speeding up what remains.
It's an ongoing battle. The JavaScript libraries compete against each other, getting faster all the time. GWT gets better and better, and has the advantage of being able to write ugly unmaintainable JavaScript per browser.
For any given task, you'll have to test to see where the arms race currently places us, and it'll likely vary between browsers.
In some cases you don't have another option. You can not rewrite everything when moving to GWT.
In a first step you could just wrap your existing code in a wrapper and if it turns out to be a performance bottleneck you can still move the code to Java/GWT
The code optimisation in GWT will certainly be better than what the majority of JS developpers can write. And when the Browsers change, it is just a matter of modifying the GWT optimizer and your code will be better tuned for the latest advances in Js technology.
Depends on how well the code is
written.
I would think so.
Generally look at the community around a 3rd party library before using it unless it is open-source (so you can fix bugs) and specifically look for posts concerning bugs - how quick do the maintainers respond to items. How long is a release cycle, etc.

Categories

Resources