Wednesday, June 29, 2011

Javascript Non Blocking development

Symptoms: You  have a javascript code that blocks your other script or even the UI.  And you are scratching your head now :)

Most of the modern browsers are using a single "thread" or "process" to handle both UI update and javascript execution (mostly update the UI as well).  And think about this "thread" as the browser UI queue, whenever you have javascript needs to be executed, it will be put into the queue along with other UI updates made by the browser.

And when the javascript code execute, everything else (other scripts and even the UI) will be waiting for that to be finished.  And if that piece of javascript code is a long running script, it will make the user experience very slow or the page will even be stalled.

There are several ways to handle this javascript blocking issue, or in the other words, we are using non-blocking javascript development.

  • The easiest one, place your script at the end of the page, before the end of the body tag.  When javascript is downloading and execute, it will halt the browser rendering, and by placing the <script> at the end of the body tag,  it will give users a full look and feel experience when the page loads. Since the <script> is at the end, so it will start downloading and executing after all initial DOM elements are rendered.
  •  Dynamic loading script.  This requires a little bit coding (yay, just a little bit). What you need to do is waiting till the DOM is ready, you create the <script> tag dynamically.  Once the "src" is executed, the browser will start to download the javascript file and execute the stuff.  In this way, the javascript won't block any browser UI, since it will yield the browser UI before download / execute.
  • If you have a very long/tight javascript loops, your loops could block the browser UI updates, or even cause the browser to stop your script.  In this case, you may want to split your loops by using setTimeout() / setInterval() to delay each execution.  In this way, all other browser UI will have a chance to be updated.
  •  Besides setTimeout() / setInterval(), you can make use of the html5 features of the webworkers.   By using webworkers, you are "outsourcing" some heavy processes to individual "webworkers".  The effect of the web-worker is opening a "new thread" for each call.

There are some links I found may help :-

Tuesday, June 28, 2011

Google+ first hand experience

Google answers Facebook recently with her new toy - Google Plus.  However, to be honest, I'm a little bit disappointed by its first impression, it looks so plain and unattractive at the first sight.   Well, since it is still lack of user base, and thus it's too early to tell the future of the Google+.  Will that be just another Google Buzz hype?? Or will it be as successful as the other competitors?

The "up" side of Google+ is it ties with all your Google services at the very beginning, so you can access all other Google service pretty much as easy as having a piece of cake. It also comes with some features like "Hangover" and "Circle" which will give yourself more privacy.  "Hangover" is you can have up to 10 friends to have video chats together (something like Skype, I bet ? ); while "Circle" is to create your own group, for example, you can only make a post viewable by certain groups of people.

Here is one blogpost in ology has more in-depth analyse on this new toy  -  

Here is a screenshot of Google Plus :

Note - One feature that I want to see in Google+ if possible
  • Can I change the theme or even better using html, css of my own to customize the UI?

Friday, June 24, 2011

CSS: Style Smartphone using @media query

There are several ways to target handheld devices.  For example, you can use javascript ways by checking the navigator.useAgent like the following

if(navigator.userAgent.match(/Andriod/i)) {
  // add a className to your <body>

But among those methods, I found the CSS @media query is my most preferable and generic ways to detect and style the page. However, if you want to target a specific one handheld system, the userAgent way (or the http_user_agent in server side ) will be more useful.

The CSS @media query method will style your page based on your screen size.  And the following is probably what you need most of the time.

/* Smartphones (portrait and landscape) -----------  */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
Styles /

/Smartphones (landscape) -----------  */
@media only screen
and (min-width : 321px) {
Styles /

/Smartphones (portrait) -----------  */
@media only screen
and (max-width : 320px) {
Styles /

/iPads (portrait and landscape) -----------  */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
Styles /

/iPads (landscape) -----------  */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
Styles /

/iPads (portrait) -----------  */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
Styles /

/Desktops and laptops -----------  */
@media only screen
and (min-width : 1224px) {
Styles /

/Large screens ----------- */
@media only screen
and (min-width : 1824px) {
Styles /

/iPhone 4 -----------  */
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
Styles */

For more robust and latest media query, please check out the following blog :)

Super Easy Sprite - Sprite Cow

Ever struggle creating Sprite as well as finding the right background-position, width and height values for that Sprite?

Now here is the tool that helps you saving tons of time from now on -  The Sprite Cow.  This service let you to upload a sprite image and then it will tell you the dimensions of each image when you select.   And better yet, for each of your sprite context, you don't need to align those at all.  Just put it wherever you like, and the Sprites Cow will tell you the position that you should put in your css.  That's easy!!!

Go to their website, and you will see a screen like that. All you need to do is to click "Select Image" and upload your sprite image.  That's all, is that easy??

Other Resources

Tuesday, June 14, 2011

jQuery UI dialog - form not post

I applied the jquery-ui dialog, but now when I click on it, the submit input ( or button ) doesn't do a normal form post.

Case Study
For example, for whatever reasons, you have html like this (just for demo purpose only)

<form name="stuff" action="whatever/listener" method="post">
   <div class="myDialog">
         <input type="submit" value="Submit" />

You applied the jquery dialog on that element as the following,

            height: 'auto',
            modal: true,
            resizable: false,
            draggable: false,
            autoOpen: true,
            width: 'auto'

Everything works fine from UI perspective... Oops, but all of a sudden, you find that the form dialog submit button is not posting to the form... What happen??

Well, first of all, before trying any methods, try to disable that dialog, and see if the form posts without it. If the form posts without the dialog, then you know you can localize the problem.

If you confirm that it is a jquery dialog issues, then I can tell you that the jquery dialog could move your DOM out of its original place, and that's the reason why the form post doesn't work.

You can move the dialog box content back to the form by doing this

Monday, June 13, 2011

CSS Hacks Mix and Match

Still remember the old days CSS hacks?  No problem if you don't remember, here is a super short syntax for you to review.

Different browsers will respond to the following css differently.

#content p { color:blue; }  // older browser
html>body #content p { color:red; } // modern browser
* html #content p{color:green;}  // IE6   ( star hacks )
*+html #content p { color:#bada55; } // IE7 (star+ hacks )
*:first-child + html #content p { color:pink; }  // IE7 ( star+ hacks variation )
html>body #content p { *color:black; }  // IE7 ( star attribute hacks ) 
#content p { color:blue\0/; } // IE8

Since developer nowadays are talking more about conditional statement, and those hacks are pretty much long gone.  However, is it possible to do a mix and match with old hacks and new methods, and is there any benefit of doing so??

If you use a conditional statement ( I'm not talking about the separate css files method ), you will have something like the followings,

.ielt9 .myClass {

.ie8 .myClass {

.ie7 .myClass {

Do you see that when using the conditional statement, you may end up having bunch of lines that look likes the above.  And through mix and match old css hacks with this modern method, you could take advantage of the benefits of conditional statement, but it could also save you more than several lines.  For example,

.ielt9 .myClass {

The above one will target browser less than ie9, and it is also taking care of ie8, ie7 and ie6 just in one shot. So in this way, you will save at least 2 definitions by using this mix and match hacks.

Sunday, June 12, 2011

Christian Burn Out Cycle

I came across an article recently - "Christian Burn Out Cycle" and found this quite inspiring, so want to share it with you guys.

Christian Burn Out Cycle Chart

This is coming from the following blog, please visit the following link if you are interested in reading more.

A Random Thought about Christian Walk

One of the most single important things in Christian life is how we behave during the hard times.

We always think we knew a lot of stuff, but not until we have a test, we won’t know what we know and what we don’t know.  Same as in our Christian walk, we may think we are pretty good in our walks;  But not until we hit bumpers, we  won’t realize that there are still so many stuffs in our lives are not “pretty good” at all.

And God reveals our weakness through the test He gave us.  Let’s make it clear, He gave test that are good for us.  Haven’t you asked God to make you a better believers?  Haven’t you pray that God give you a servant heart??  Haven’t you asked God to give you more love??

Yes, now how about God answer your prayer and He gives you a test and reveal your weaknesses??  What would be your response??

  • A) Oh what??  How this can be happen to me ??
  • B) God,   I don’t know why this happen to me, but I know it has a meaning to me.

So, imagine you are now in mid-term test of a Maths Class.  Your end result shows that you are pretty weak in trigonometric.  What would you do next??  I bet you would go back and study more on that topic before the final comes.  So in this sense, the mid-term is a way to tell us what we need to improve.

Saturday, June 11, 2011

Latest jQuery plugin - HTML5 Spin Wheel

Just created a new jquery plugin just for fun recently. Part of the algorithms are taken from some other places. What I did here is just playing around with the HTML5 canvas, but somehow I also package that as a jquery plugin.

Here is the demo below:-
Try to enter the things you want to put on the wheel, for example,

  • Where to go to lunch today
  • Who is going to wash dishes today
  • Who is paying for lunch today
  • ... etc

Press Add to add more items.  After adding all your items, you can click the spin.

Feel free to modify the source as you will.  There is an array of applications that can be based on this plugin.  For example, you can integrate that with Yelp to create where to go to lunch today.  This plugin is just a simple demonstration of what HTML5 is capable of, but HTML5 is far powerful that just that.

IE User Note: 
It is recommended you use the latest (modern) browsers, like Chrome / Firefox / IE9, because HTML5 is still relatively new stuff, older browser may not support those at this point.  There are some libraries that can make your browser to recognize HTML5 tags, in our case of canvas, you can take a look at the Google's ExplorerCanvas.    

Friday, June 10, 2011

Latest RequireJS throws Mismatched anonymous require.def modules

Latest RequireJS throws Mismatched anonymous require.def modules

Here is a list of known situations where this error can occur:

1) You are using the loader plugins or other anonymous modules in your code, but you do not use the RequireJS optimizer to concatenate files. The RequireJS optimizer knows how to name anonymous modules to avoid this error.

2) If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.

3) Also seen if you manually code a script tag in HTML to load a script that has a few named modules, but then try to load an anonymous module that ends up having the same name as one of the named modules in the script loaded by the manually coded script tag.

And if you are upgrading from older versions, you may be still using require.def() function, try to change to use the define() function instead.  And also, for your modules that using define() function, please check if you are using order!,  you probably want to take that out.  In the old version require.def() won't throw error when you use order!, but after I upgrade to the latest version, and it throws error when I include order! in my define() function.  So in my case, it fixed after I took out all the order! from my define() function. I believe the order! is not suppose to go into the define() function, as I didn't see that mention at all in the documentation.

For more information, please read the RequireJS documentations.

Thursday, June 9, 2011

What's it like to be recruited? ( by Brace )

This is from my email thread (by Barce), and since it is so funny, I post it to my blog :)

First off, I'm very grateful to my parents for getting me a computer when I was 8. I am not sure where I'd be if it wasn't for that.

I got inspiration from this HN article and did the same. My #s are way higher.

As an experiment, I submitted my resume to dice, monster and careerbuilder seeking a Ruby on Rails application developer position.

The result:
Monday: 46 calls, 22 voicemails, 39 emails.
Tuesday: 58 calls, 13 voicemails, 42 emails.
Wednesday: 23 calls, 11 voicemails, 34 emails.

I turned off monster, dice and careerbuilder at 11 am on tuesday and I'm still getting calls & emails.

Recruiters were submitting resumes to one particular job twice without my permission. This happened 4 times and is definitely unethical behavior. It hurts candidates b/c you can't interview at these places anymore.

The question I've asked is: how much are you willing to offer?

Most of the jobs are in the 80k - 100k range.

This means that if you got to a startup with no recruiter and are making 120k, the recruiter's company is making 20k - 40k on the sale of you.

The better recruiters have connections to companies mentioned in Techcrunch and these are at the 130k range and up.

The best rates are at Fortune 500 companies, where 200k is market. Heck, you can get an HTML5 / CSS3 position at one and get that rate.

Another question: How long has this job been advertised?

Sure demand is high, but a great job will never be

The technology:
I totally agree with folks who say that Facebook has made us closer, but recruiting technologies and its industry have made hiring managers and candidates farther apart. Someone or a group of people need to create a technology to disrupt this awful industry of selling people.

Recruiters are people who are trying to solve a pattern matching problem with crappy tools, but the better those tools get, the more in jeopardy their jobs are.

How I feel? I feel objectified. It's hard to swallow the image of a bunch of douchebags submitting your resume for jobs you never applied for.

I guess this is what it's like to be extremely attractive woman who has just become single. Some of the recruiters are total players and won't leave you alone when moving on would be more efficient and a better bet. Others are really, really bad, and you can tell they are reading lines from a script.

The recruiters I go with work like this:
1. They tell me *their* story. Why are they in recruiting? What do they want out of life?

2. They really listen. This means asking questions like, "How is Javascript different from AJAX?" Or deciding that what is on paper doesn't match what they are hearing, and that you're underselling yourself.

3. They get you lunch for your time. This is totally optional, but very nice.

4. They wrap up the meeting by telling you something about you that you might've not known about. E.G. one recruiter told me that I saw myself as more than just my job and that I like to protect people.

5. They are very efficient without seeming so.

What to do instead:
If finding a job is a pattern matching problem, and you are a coder, then code that regex that brings you the job of your dreams.

You're looking at 20k - 40k more / year if you can just cut out the middle.

Les Paul Playable guitar seen in today's doodle

They are using HTML5, javascript and Flash.  It can be done by HTML5 and javascript alone, but they use Flash because of some older browsers doesn't support HTML5.

If you go to view source, you should see this
<canvas width="474" height="175"></canvas>

They are using a <canvas>- Might be to draw the guitar. And then a javascript call google.doodle.go(); on the click.

Monday, June 6, 2011

Getting nodeName from jQuery

Below method won't work
$('.myClass').nodeName;  // it will return undefined

The reason is you are calling a "property" that is not existing in the jquery object.


The correct way to do this is



Saturday, June 4, 2011

Two Choices

Still remember the days in school?  When the final exam is coming and you are still not well prepared.  Are you the person that says
  1. I need to study hard even though time is not enough, just try my best.
  2. Oh man,  I will fail the exam, and think about many "if-s" what will happen next when you fail the exam.

In Psychology, there is something called "self fulfilling prophecy", which is a prediction that directly or indirectly causes itself to become true by your behavior / actions. If you keep thinking something is going bad, it could eventually go bad, because your thinking is sufficient enough to affect your behavior.  And it could be yourself that eventually that force something originally good to become bad.

If today you have something you cannot control in your life, instead of being paranoid by your thoughts, do you want to spend a minute today and cast that burden and worry back to our Heavenly Father? He cares about you. And you always have choices.

A Random Thought on Spiritual Strategy

Sometimes I heard people says “Attack is the greatest Defense”. Yes, I agree with that. However, is that also true for Spiritual world??
If you think you can be a hero and can do all great things alone, I probably will say “No” to you (for the question at the beginning). Because I don’t think God wants us to be a “Spiritual Terminator” in His kingdom. We all are Warriors in His kingdom, but no one will be “the one” warrior.
So it implies a team work.

But at the same time, it involves other problem, which is, you guess it right, it is the people.
Let's imagine 2 examples and you can guess what kind of trouble people are making when they are doing the “team work”, each item has chained consquences, just use your imagination :-
Case A:
Let’s say there are 10 people in the group, and there are 10 things need to be done, which way you think is more efficient?
  • 10 people doing 10 different things at the same time
  • 10 people working on the same item, for 10 times, one by one?

Case B:
The same 10 people in the group, and they need to pick 3 out from the 10 items
  • Should a particular person dictate which 3
  • or, should all 10 person each cast their votes

So, just use your imagination to think about each options in both Case A and Case B :)  I won't say more here.

Probably at the end, team work may be even harder for this community. And eventually, there may be a need to have a “spiritual terminator” coming out periodically in order to give a boost to the community, and each of them will probably burn out easily and quickly.

What do you think about this?  

Friday, June 3, 2011

HTML5 Canvas rendering issue in Firefox

Doing a benchmark on canvas rendering performance in both firefox and chrome.

From a normal user perspective
  • The Chrome runs very smooth in rendering.
  • The Firefox runs very slow and have some hiccups.

But when I check on the resources usage
  • The Chrome itself takes more resources, but the Xorg usuage seems very light.
  • The Firefox itself takes half of the resources as chrome, but it jack up the Xorg usuage by alomst 1000% (10 times) 
It gives me a suspicious that, when Firefox rendering the canvas, it tries to make use of the operating system / hardware capabilities to render the canvas ( in other words, off-load the works to the OS or the hardware acceleration), which may in return slow down the rendering capabilities of the browser.

Well, please correct me if this suspicious is not correct :)

Below is the "top" result when I run my testing, and the result is quite consistent.

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND          
 1317 root      20   0 86604  25m  11m R   66  0.7   5:22.87 Xorg            
 2376 ryu       20   0  464m 129m  34m S   59  3.7   4:08.18 firefox-bin      

 3594 ryu       20   0  142m  34m  15m R  100  1.0   0:24.03 chrome          
 1317 root      20   0 79428  26m  12m S    6  0.8   5:33.05 Xorg


For those of you who just want to increase the performance of Firefox canvas rendering, try using the suggestion in the following blog.

For Chrome before 11, the canvas 2d is not using hardware acceleration, but you can turn that on, please try the following blog.

Thursday, June 2, 2011

Another Post about IE7 z-index bug

Yep, this is about the well known IE7 z-index bug, and some people called it a stacking bug.  I'm pretty sure there are a lot of posts out there will tell you how to fix the problem. And in this post I will briefly explaining my experience dealing with this bug, and my observation of this bug's behavior.

Imagine a Scenrio
Imaging you have a image gallery ( let's say a 3X3 grid ).  And in each grid, besides the image, there is another hidden div (position : relative) in which the div will appear when you mouse-over the image (let's call this hidden div an overlay div). Since you want that hidden div, when it appear, to be on top of the grid, so you use the "z-index" attribute, let's say you put "z-index:99999" for the hidden div.

Image the 3X3 grid looks like the following :-
1, 2, 3
4, 5, 6
7, 8, 9

Well, it's all working great in FF and Chrome, but when you test that in IE7 ... you found out that the overlay div is above the image in the same grid, but the same overlay div now goes below the image of the right grid. On the other hand, the overlay div on the right always  goes on top of the image of the left grid. And no matter what z-index you use, this behavior is still the same.

Well, let's put it in this way in order to make it more visualize :-
G = Grid

G(1).Overlay > G(1).Image
G(1).Overlay < G(2).Image

Why this behavior??
After reading some articles and do some testing, in IE7, these are the behavior
  • IE7 will reset z-index when you have declare "position" in your elements
  • In IE7, children's z-index will never be higher than the parent

Since it re-assign z-index at run time when it sees appropriate, so it means it will overwrite whatever is in your css. 

So in our case, the IE7 has assigned the 3X3 grid with the following z-index value
0, 1, 2
3, 4, 5
6, 7, 8

And since the Children's z-index value will never be higher than the parent, so in Grid(1), even though my overlay div has z-index:99999, it nows become irrelevant because of the z-index rearrange rule.

So the item from Grid(2) is always having a higher z-index value than all elements inside Grid(1), and item of Grid(3) is always having a higher z-index value than all element inside Grid(2) and Grid(1) and so on. 

How to fix that issue?
Well, there are so many ways, and just be creative. The way I fix it is using javascript like this
  • count how many Grids
  • reassign z-index value starting the largest number
8, 7, 6
5, 4, 3
2, 1, 0

In this way, we just un-do what IE7 has done to our 3X3 grids.

There is another solution seems much easier, since IE treats a position like a z-index reset, so you can declare position of static on the parent element containing the z-indexed elements to have them respond to z-index correctly.

There are so many solutions,  and are totally depending on your needs and your creativity :)  

Fancy diff command with sed

Of course you can just use a simple diff to output the difference between files. But how about if one day you need to generate a custom report from that diff, for example, what is the line number difference between the files?  Well, you may need some diff commands like below to save your day.

Don't be scared by this command. Once you break it down and it is quite easy to understand.

diff file1.txt file2.txt --changed-group-format='line %dF to line %dL is different|' --unchanged-line-format='' | sed 's/|/\n/g'
  1. --changed-group-format  ~ what to output if the line is different
  2. --unchanged-line-format ~ what to output if the line is the same
  3. - sed is a text manuplulate program.
Note : Thanks nano for the comment

The output will be something like
line 2 to line 1 is different
line 7 to line 6 is different

A brief introduction to sed
sed is used for manupulating strings, for example, you can remove lines, append lines, subsitute string ... etc. You can also use regular expression to  filter your strings ( well, actually regular expression is the most used case for sed ).

Here is a simple sed command

cat mood.txt | sed -e 's/happy/happier/' > mood.txt

This command read the output from mood.txt, replace all happy to happier, and then replace what is inside the mood.txt.

The parameter -e  means using the following criteria / command.

cat mood.txt | sed -f myCommand.txt > mood.txt

The parameter -f means using the commands in the file as the criteria.  So for example, if you have bunch of commands, you can write that into a file.

Well, sed is much more powerful than just the above, keep exploring you will find more ~

Wednesday, June 1, 2011

How to create your Custom Event in jQuery

If you have used jquery before, I believe you should be very familiar with using events like the following:-

    // doing something here


$('.myOtherClass').bind('mouseenter', function(e) {
    // doing something here

But do you know that you can create your own Custom Event and call it just like a standard events.

$('.myAnotherClass').bind('SuperClick', function(e) {
    // doing something here

and somewhere in your code, you can call your custom event 'SuperClick' like this


That's it, you can bind your custom event to your element (object), and next time when you trigger that custom event, your stuff will run. However, don't think too complicated if you are still not sure what's going on... Think of it as if you are just creating a javascript function and you can reuse that function whenever you call it.

But there is a catch when you use this type of custom event, make sure you trigger the custom event using the same element.  The reason is you bound the custom event to an object (element), and only that element can listen to that custom event.  Make sense?