I am trying to develop a application that has quite a bit of client side based scripts. The page has sections that interact with each other based on different inputs. The problem is when you get alot of content on the page the page slows down DRAMATICALLY in IE7 due to the poor javascript engine integrated with this browswer and also partly, becasue there is quite a bit more data on the page.
I am already using web services for anything I can, JQuery with ID based selectors and as little effects and animations as I can.
Do you guys have any tips that I could use for optimization of this?
A couple off-the-wall suggestions...
Flash as coprocessor. If you have computationally expensive things to do, you can hand them off to Flash. The ActionScript is going to be faster than IE's lousy JS. However, be aware that if you transfer much data back and forth between JS and Flash, it's very slow.
Google Gears. You can speed things up with web workers. When you detect IE7, say that upgrading to IE8 or installing Google Gears will improve the experience.
Possibly Silverlight could be used as a coprocessor. I don't have experience with it, however.
Can you even tell what's slow? Is it when you touch the DOM?
Run your code in a profiler and see what it is actually doing. See where your time is spent. IE8 provides IE7 compatibility and a decent profiler included in its Developer Tools.
To do the profiling in IE7 directly you will have to mess around with Visual Web Developer or the debugger bundled with MS Office. More fooling around is necessary, but it is possible to get it to work. Every time I have needed to set this up on a new computer it has taken me an hour or more to figure out the magic incantation to make it work, but it is doable.
I kind of feel like maybe some of these answers might be missing the obvious.
What is the efficiency of the algorithm you are using? Linear? Logorithmic? exponential? It seems to me, that if it's the JAVASCRIPT that's getting slower, as the document gets larger, then it's the efficiency of YOUR code that's the problem, not MS's. IE javascript is slow, but what makes you so sure that it's specifically a problem with that browser? Do other javascript engines do okay with it?
Without knowing a single thing about what you're doing or how you're doing it, one way to go is to trade off memory usage for speed- Cache previous results, and other optimization strategies which you can find lying around if you read this book or that website about programming.
Another thing to keep in mind is that dom interaction is really slow. If you can reorganize your code to achieve the same thing, but with fewer manipulations in the dom, that will improve performance
Some pretty regular gotchas pertain almost exclusively to the DOM, which is slow accross browsers. Try to user innerHTML wherever possible. It's not the standards-compliant way of doing things, but it is by far the fastest.
If you're looping through DOM elements using something like the following:
for (var i = 0; i < domNodes.length; i++) { ... }
Note that every time you request the length of a NodeList, a rather expensive lookup operation is performed. You're better off caching the length of the NodeList as follows:
for (var i = 0, il = domNodes.length; i < il; i++) { ... }
The performance improvements here are incredible. Robert Nyman did an interesting comparison of for loops. If you've never heard of this, the performance boost might surprise you.
This is an excellent google tech talk video on javascript optimization by javascript guru Nicholas C. Zakas
http://www.youtube.com/watch?v=mHtdZgou0qU
He advises you to use local variables to limit scope lookup, keep javascript css style changes to a minimum(change classes instead) and do them in batches if you have to to reduce browser re-rendering, and lots of other great tips :)
Attach and detach events as needed and do not use behaviors. Also create threads to speed up UI using setTimeout and setInterval. I do this all the time to prevent IU choppiness.
Related
Is there a way to check the resource usage with a javascript code?
Can i check RAM usage and cpu usage of the script?
Since there are various ways to do something, i might write the code using different methods, and save it in as 2 different files, and check which method is more optimized. Esp when i'm calling a function recursively.
This way, i'll get to learn which methods are better and what to use.
Anything like maybe an addon, or maybe a script to be added that does this. It would be much better if it shows function wise. I'm not sure if something like this exists.
On a note, with chrome inspector, i tried CPU profiling, but it seems to show me values according to time, and does not show the RAM/CPU usage.
There's no uniform cross-browser way to do this. You can get an overall sense of your javascript performance by using Chrome's Timeline tool. Switch between the Timelines and Memory tabs on the left and hit the record button at the bottom. I believe Safari has a similar tool.
Internet Explorer has the excellent DynaTrace tool, although I don't know it well enough to provide detailed instruction on how to use it.
Note that javascript interpreters vary wildly in implementation, so they may have very different performance characteristics. Rather than get caught up in the details of implementation (premature optimization is evil and all that), write your code with good coding practices in mind. That means that if you do have performance bottlenecks (which the profiling tools available will help you locate), you can refactor more readily.
I don't know any specific way to test the Ram and CPU stats of javascript. But I often user http://jsperf.com/ to see how two different functions perform.
Have you tried with Crome Tools > Task Manager in Chome Tools menu options? It shows the CPU and Memory Usage for each process running in the borwser (comprise chrome-extensions).
During the past few months, I've been working on a large web application. Repeatedly, we've written code that, according to DOM & JS specifications, should work perfectly, but still manages to completely kill one or more of our test browsers -- recently, we produced pure JavaScript code that should have been harmless but causes General Protection Faults in IE8, other pieces of code that completely freeze Safari, etc.
Well, we'll solve each issue, item by item, with as much blood, sweat and code as it takes. But the question I have in mind is the following: is there a knowledge base on such browser frailties? Something comparable to quirksmode.org, but with guidelines on how to code stuff to avoid killing our browsers?
Thanks.
edit Precision: not that it changes anything to the question, but we're using jQuery.
You've probably already been down this road, but most of the major libraries like jQuery, Prototype, YUI, Closure, or any of several others are going to have run into most of these issues and coded around them for you already.
If you are writing manual DOM/JS, please use a library as T.J. Crowder mentioned. These libraries solve nearly all the common inconsistencies between DOM libraries and make a usable sugar sweet API layer on top.
I have listed a bunch of websites that document cross-browser bugs in a previous answer.
what basic tips should we observe in design web pages(html/css/javascript) for having highest compatibility with most browsers(IE-firefox-opera-chrome-safari)?
thanks
Validate often and squash all validation errors by the time you make a public release. The purpose of validation, after all, is to parse the html as a standards-compliant browser would and then avoid the errors that a browser's parser would find.
Apply progressive-enhancement techniques. Often that means moving some of the complexity of dynamic pages to the back-end (e.g. php, django, what have you) so that you can have complex functionality that doesn't break in one of the thousands of different client environments in which a page's javascript will run. jQuery is excellent for narrowing the focus of your javascript development towards feature enhancement instead of open-ended features-in-javascript, and it'll help with cross-browser compatibility as well.
IE - Test in at least one live version of IE 7 or 8. Unfortunately, there really isn't any way around this, because even IE8 misbehaves like no other browser. If possible, limit your goal of support for IE6 to html/css (i.e. don't promise support for user-enhancement-features via javascript in ie6). If possible, drop support for IE 5.5 and below.
For Javascript, use libraries that are intended on being platform-independent (ie: JQuery, Prototype). Not everything will be, but it'll make your life much easier.
For CSS, I'd say follow standards, but IE tends to cause problems across the board.
Which means, you need to test, and test often. Selenium is awesome for automated functional testing, and it works with pretty much every browser. We use a Selenium RC server on a Windows machine to test IE and Firefox, which are then controlled from our standard Java JUnit tests.
Keep things simple.
The simpler your markup, CSS, and JavaScript, the easier it will be to track down incompatibilities. Try to limit yourself to CSS1 for as much as possible. Only use more modern CSS2/3 features when there is no easier way to accomplish your task.
Don't use tables, they just add extra complexity. Using semantic markup not only makes things maintainable, but also gets you the best cross browser support if done properly.
Keep in mind that floats are evil, but are also very powerful. Use them generously, but avoid trying to clear floats. Use overflow instead.
Use a JavaScript framework. Framework developers have smoothed out most of the cross-browser bugs for you. I recommend jQuery, but you can choose any framework your developers feel comfortable with. My advice is to:
Use a JavaScript framework that doesn't alter the prototypes of native objects (like Prototype JS does)
Doesn't introduce many global variables. Most frameworks follow this rule.
Aside from those 2 rules for JavaScript, try using closures to encapsulate code so you don't introduce your own global variables.
One strategy I use is to start my CSS with a set of rules that blank everything out. Each browser may have different values for element attributes so ensuring that everything is consistent from the get-go can be handy. Here is an example reset.css
http://meyerweb.com/eric/tools/css/reset/
Take a look at this great article: Browser Compatibility Tutorial
Remember: something won't just work for a specific browser (mayble a left dotted border won't show in Chrome). Do not be upset about that if you can! :) Cross-compatibility is an art that takes a lot of time.
I am currently half-decided to use Kohana + Zend as needed for the PHP part. What I would need next is an excellent base for JavaScript code. There are a bazillion of contenders here and choosing isn't exactly as easy as with PHP.
I would need practically everything from form posting and retrieving results to skinnable widgets and animations. For this reason using multiple libraries will probably be a must, as no one framework can do it all. The requirements I have would be this (initial list):
Good browser support. WebKit-based is hardly an issue and Firefox 3+ is good. However, I'm looking at you Internet Explorer. IE 6 can be ditched, seriously, but 7+ support is needed.
Good performance. While WebKit has had a stupidly fast JS implementation for quite a while (and Chrome even before), Firefox has only recently got TraceMonkey and don't even get me started on Internet Explorer. While it is true that you can't do much about IE as anything will be slow, I don't want to try running Chrome Experiments in the others either.
Excellent support. This is a total must. The better the support, the more inclined will I be towards a library.
I am currently looking into jQuery as it is a very neat library, but the quality of plugins is questioned by some. Processing.js looks extremely promising, but IE does not support canvas, thus something has to be done about that and I am not sure how it could be replaced.
Go with a known library that is used by many sites. This will ensure all 3 of the points you have mentioned.
Personally, I would go with jQuery for these above reasons:
Great cross browser support
Good performance, as it is a thin api layer
Excellent support. Good documentation, loads of other devs
Although jQuery seems to be the most used library these days, there are other very good candidates as well.
One of them are YUI Library.
YUI has excellent documentation, and support. And the source code is really good.
YUI is developed by Yahoo!, where Douglas Crocford is architect (the author of JavaScript: The Good Parts, and the man behind JSON). Yahoo! is well known for their focus on JavaScript development.
YUI has good browser support and is fast and robust.
If it's war simulation and you have custom objects that you want to animate beyond the simple CSS effects and animations, then canvas tag is your best bet. It's as close as you can get to Flash but much more smoother. Processing.js looks really good for manipulating the canvas.
If that's the core component of your game, then I see the other libraries as adjunct to Processing.js that can be scrapped out without any deep commitments. That said, jQuery is great if you're dealing heavily with the DOM. It has really good support and community. MooTools is highly modular and has been traditionally strong with animations. YUI is a great library too, but a little verbose for my taste. Thought, Yahoo has made heavy changes with v3 to fix that. And a bunch of other libraries, that I don't use at all.
Dojo is a great library for writing web applications; however, never having written a game, I'm not sure if it is well suited for that sort of application. I must warn you though that the Dojo documentation is crap. Absolute crap. On the other hand, things like dojo.hitch, dojo.require, and dojo.partial are absolute joys.
I would try to avoid using cross-cutting libraries (like Dojo+jQuery) as much as possible. There's not really a good reason to do it and will create bloat and confusion in your application from day one.
That said, using multiple, non-overlapping libraries does make sense for a project like this. You might want to look into using Processing.js for visual needs and either Dojo or jQuery for your core.
Some other things to consider. Targeting IE, even IE8, for JavaScript game development is a bit ridiculous because of its slow performance and lack of canvas support. Also, according to John Resig, developing games in JavaScript is hard.
Have you considered being a pioneer (wink) and trying something out in 03D?
Given the iPhone's 25k limit for caching of files, I'm wondering if there's interest in an iPhone optimized javascript library that makes caching a top level goal. Since it'd be iPhone only it could get rid of most cross-browser cruft and rely on safari specific capabilities, hopefully cutting down some of the girth and staying with 25k.
John Resig discusses this briefly, although mostly to dismiss it, it seems. He does mention:
if you're particularly excited about
breaking jQuery down into little
chunks you can grab the individual
pieces from SVN and build a custom
copy.
Anyone tried that?
Dojo implements a 6k version that seems to rely on deferred loading. I'm mostly a jQuery user so I haven't given it a try, but it looks interesting.
Overall: what do you think about a safari/iphone specific javascript library that implements, say, the top 90% most used APIs in jQuery (or your other favorite library)?
Newer update: looks like Zepto is the way to go these days.
Found XUI, looks like what I was looking for, although I haven't given it a try yet.
You should check out QuickConnectiPhone. It may do what you want. It can be found at https://sourceforge.net/projects/quickconnect/. It also lets you write your app in JavaScript, CSS, and HTML and yet install it on a device.
There is an API that will allow you to make calls down to the Objective-C layer as well for phone vibration, GPS locations, accelerometer information, and some more. You can even extend this to other native phone behaviors as well.
The development blog for the framework is found at http://tetontech.wordpress.com
I'm experimenting with XUI as well, looks promising, seems to follow JQuery-way of doing things.
The same people also created 'lawnchair' for persistant storage of data in json format, XUI+lawnchair looks like a great combination for cross-platform (as in at least iphone+android, maybe webos, symbian, blackberry and ms as well) mobile development.
I think it would be fantastic, but it would be hard to match the testing and reliability of jquery unless someone really picks it up and runs with it. If there was a lightweight, safari only version of jquery that was completely compatible with the plugins and documented methods, it would be a godsend.
Given the increasing popularity of the iphone, I think it would be a really useful thing, it might be possible to remove the cross browser stuff and get it down to size.... however, it would be even more useful if the iphone had a more realistic cache limit.
It does make me wonder if the cache limit in the iphone was determined by the capacity of the hardware or the business needs of the carriers. A 50K cache limit would reduce a lot more carrier usage...