Best javascript questions in March 2012

Why is jQuery.ready recommended when it’s so slow?

22 votes

I have asked a similar question before but I never made my point exactly clear, or at least I think it’s such a relevant question that it’s worth to bring it up and see if anyone can give some insightful thoughts.

When using jQuery, many of us use the jQuery.ready function to execute an init when the DOM has loaded. It has become the de-facto standard way of adding DOM manipulation programs to a web page using jQuery. A related event exists natively some browsers, but jQuery emulates it in other browsers, such as some IE versions. Example:

<head>
<script>
    var init = function() { alert('hello world'); };
    $.ready(init);
</script>

Now, all our tests show that this event can be quite slow. It’s not nearly as slow as window.onload, but it’s still often around 100 ms delay before execution. If FF it can be up to 200-300 ms, especially on refresh.

These are some very important milliseconds, because this is the amount of time the initial layout is shown before any DOM manipulations are made (such as hiding a dropdown). Many times, a layout "flicker" is mainly caused by using a slow DOM ready event, forcing programmers to hide elements using CSS instead and potentially making it less accessible.

Now if we instead place an init function in a script tag before closing the body tag, it will be executed much faster, usually around half the time but sometimes even faster:

<head>
<script>
    var init = function() { alert('hello world'); };
</script>
</head>
<body>
<!-- some HTML -->
<script>init();</script>
</body>

A simple test page that proves the differences: http://jsbin.com/aqifon/10

I mean, we are not talking about barely noticeable differences as some of the "optimization police" promotes when it comes to using effective selectors. We are talking about some major delays when doing DOM manipulations onload. Trying this example in FF, domready can sometimes be more than 100 times slower (300ms vs 2ms).

Now to my question: Why is jQuery.ready recommended to use when it’s obviously much slower that other alternatives? And what are the drawbacks of calling the init before closing the BODY vs using jQuery.ready? It’s arguably more "safe" to use domReady, but in what context is it more safe than the other option? (I’m thinking stuff like document.write and deferred scripts) We have used the BODY way for nearly 5 years on many client sites, and we never run into any problems. It’s just a lot faster.

I’m also wondering, since there is so much fuzz about jsPerf and optimizing selectors for a couple of ms per 10000 executions, how come there is not much talk about this? It’s basically the first delay the user faces, and it seems to be fairly simple to slice 50-100 ms on each page load...

To the point first:

No, there is no disadvantage in calling you init before closing the <body>. It will as you have noticed perform better that relying on $.ready() and will also work with all the browsers flawlessly (even on IE).

Now, there are however reasons to use $.ready(), which in your case they do not probably apply:

  1. $.ready() makes it easy for developers to do stuff in the right order. In particular, the critical thing is to not reference DOM elements that have not been loaded. While this is simple enough, lots of developers still find it confusing. $.ready() is a no-brainer, albeit a slow one.
  2. In you have say several scripts that need to init(), it is not necessarily easy/convenient to manually do that at the end of your body. It requires discipline and knowledge of what these scripts do. In particular you will often see $.ready() in libraries dependent on jQuery, since it makes things work no matter what way developers will use to load the libs.
  3. With Asynchronous Module Definition (for instance require.js) becoming popular as a way to load your javascript, the end of <body/> method is not guaranteed.

Can 'this' ever be null in Javascript

21 votes

I have a function along the lines of the following:

    doSomething: function () {
        var parent = null;

        if (this === null) {
            parent = 'some default value';
        } else {
            parent = this.SomeValue();
        }
    }

Could parent ever be set to 'some default value' or is the check for null superfluous?

Alternatively, what if I used the less restrictive:

    doSomething: function () {
        var parent = this ? this.SomeValue() : 'some default value';
    }

Could parent ever be set to 'some default value' in this case?

In non-strict mode, this has undergone an Object(this) transformation, so it's always truthy. The exceptions are null and undefined which map to the global object. So this is never null and always truthy, making both checks superfluous.

In strict mode, however, this can be anything so in that case you'd have to watch out. But then again you have to opt in for strict mode yourself, so if you don't do that there are no worries.

(function() {               return this; }).call(null); // global object
(function() { "use strict"; return this; }).call(null); // null

The specification of ES5 says:

The thisArg value is passed without modification as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value.

Reference - What does this symbol mean in JavaScript?

20 votes

What is this?

This is a collection of questions that come up every now and then about syntax in JavaScript. This is also a Community Wiki, so everyone is invited to participate in maintaining this list.

Why is this?

Stack Overflow does not allow searching for particular characters. As a consequence, many questions about operators and other syntax tokens are not found easily when searching for them. This also makes closing duplicates more difficult. The list below is to help with this issue.

The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them, not to copy over content from the ECMAScript Spec.

Additionally, this is a blatant copy of the PHP symbol reference. We needed a JS one.


Please help. Edit and add links to other operators/syntax references, or if you can't find good questions/answers on a particular piece of syntax, add an answer to this question and link it

MDN reference on operators

The List

== Equality Operator


=== Equality Operator


!= Inequality Operator


!== Inequality Operator


&&, ||, ! Logical Operators


!! Logical Operator


, Comma Operator


var x = function() vs function x() Function Declaration Syntax


(function(){...})() IIFE (Immediately Invoked Function Expression)


| & ^ Bitwise OR, AND, & XOR operators


<< >> Bit shift operators


[], Array() Array Notation

Why does $($) crash my page?

18 votes

Disclaimer: Do not try this at home


Why, if I am using jQuery, does $($) freeze the page?


Inspired by this Area51 question

$($) is a shortcut for $(document).ready($). So, it will run the function (when the DOM is ready or directly when this is already the case).

The function passed to .ready is passed the jQuery function for convenience (especially useful when you're in noConflict mode). So, $($) will call $ with $ as argument - and everything will happen again, which is endless recursion.


Another explanation:

  1. You call $($).
  2. jQuery adds the function argument ($) to an internal ready list.
  3. Some time later, jQuery sees that the DOM is ready and thinks: "Let's call all functions in the ready list".
  4. The only function in the ready list is $, so it calls $.
  5. jQuery sees it should pass the $ function as the argument to those functions.
  6. It calls $ with $ as argument.
  7. The $ function sees a function as its argument, but because the DOM is ready, it calls the function directly (there is nothing to wait for).
  8. The function is called with $ as the argument.
  9. Everything happens again since step 7 applies.

Why JavaScript function declaration (and expression)?

14 votes

I've seen others using the following pattern.

var bar = function foo(){};
console.log(bar); // foo()
console.log(foo); // ReferenceError: foo is not defined

But why? I can see the point if both were declared, but they're not. Why is the reason?

As mentioned by others, using the first form in your example (a named function expression) can help with debugging, although with the recent improvements in built-in developer tools in browsers, this argument is becoming less persuasive. The other reason for using a named function expression is that you can use the function name as a variable within the body of the function rather than the now-deprecated in ES5 arguments.callee.

However, named function expressions are incorrectly and problematically implemented in Internet Explorer < 9 and should generally be avoided when you're targeting those browsers. See Juriy Zaytsev's excellent article on the subject for more information.

"".split(" ") in SO's javascript

13 votes

I've seen a lot of idioms, most of them clever and logical once explained. But while I was looking over SO's javascript to get some ideas about good interface design I saw the following line:

initTagRenderer("".split(" "), "".split(" "));

Which really threw me for a loop. Obviously, they initialize the tag renderer with two arrays containing exactly one null-string argument (or [""], which "".split(" ") evaluates to). That part I understand (having done the same thing in my own code). But it seems like passing a literal would accomplish the same thing.

Is there some non-obvious reason for doing this that I'm failing to see as a newcomer (to js, not programming)?

Also, I did try searching, and got lots of info on split() itself (which I already understand quite well), but not the idiom; Googling for double quotes is pretty fruitless.

Edit: It was the obvious answer. This part of the code is dynamically generated, and is not usually populated on SO proper.

There is probably server-side code that dynamically populates those arguments to look something like this:

initTagRenderer("javascript php".split(" "), "ruby lisp".split(" "));

What that function does, I have no idea. But it must require an array of tag names, and it's easier to generate a space-delimited list rather than a JS array literal.

Edit

After some heroic investigating, it appears that initTagRenderer does indeed nicely format question tags. Tags that match a name in the first parameter are given a required-tag class, and tags that match the second parameter are given a moderator-tag class.

According to Madmartigan, it's used on meta:

initTagRenderer(
     "bug feature-request discussion support".split(" "),
     "faq status-completed status-declined status-bydesign status-norepro status-reproduced status-planned status-deferred status-review featured community-ads".split(" ")
);

View example


Relevant (but minified) line of full.js:

function initTagRenderer(f,c){window.tagRenderer||(window.tagRendererRaw=function(b,g){var g=g||"",e="";g||(f&&-1<$.inArray(b,f)?e=" required-tag":c&&-1<$.inArray(b,c)&&(e=" moderator-tag"));return"<a class='post-tag"+e+"' href='"+g+"/questions/tagged/"+encodeURIComponent(b)+"' title=\"show questions tagged '"+b+"'\" rel='tag'>"+b+"</a>"},window.tagRenderer=function(b,c){return $(tagRendererRaw(b,c))})}

Is Knockback.js production ready?

12 votes

I've used Backbone.js, I've learned about Knockout.js; however, now I found out about Knockback.js. It is supposed to get the best out of the other two tried& proven frameworks. Do you have any experience with Knockback in production? I'm wary to use it since it doesn't seem to be mature enough.

I wouldn't use it yet. It's hard enough to get corporate buy in on knockoutJS.

I guess it all has to do with the size of your company, the willingness to support alpha / beta / volatile open source projects.

It is the nature of the beast, this bleeding edge of innovation. Skating that thin ice of unsuportability.

Is it better to use .delegate() performance wise?

12 votes

One of the developers I work with began to write all his code this way:

$('.toggles').delegate('input', 'click', function() { 
   // do something  
});

vs:

$('.toggles').click(function() { 
   // do something  
});

Are there any performance benefits to doing this?

delegate() is superseded as of jQuery 1.7.

Use .on() instead.


.on() has excellent performance benchmarks. And covers your .click() needs as well as needed

function* in JavaScript

10 votes

In this page I found a new JavaScript function type:

// NOTE: "function*" is not supported yet in Firefox.
// Remove the asterisk in order for this code to work in Firefox 13 

function* fibonacci() { // !!! this is the interesting line !!!
    let [prev, curr] = [0, 1];
    for (;;) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

I already know what yeild, let and [?,?]=[?,?] do, but have no idea what the function* is meant to be. What is it?

P.S. don't bother trying Google, it's impossible to search for expressions with asterisks (they're used as placeholders).

Thanks!

It's a proposed syntax for EcmaScript.next.

Dave Herman of Mozilla gave a talk about EcmaScript.next. At 30:15 he talks about generators. Earlier, he explains how Mozilla is experimentally implementing proposed language changes to help steer the committee. Dave works closely with Brendan Eich, Mozilla's CTO (I think), and the original JavaScript designer.

You can find more detail on the EcmaScript working group wiki: http://wiki.ecmascript.org/doku.php?id=harmony:generators

The working group (TC-39) has general agreement that EcmaScript.next should have some kind of generator iterator proposal, but this is not final. You shouldn't rely on this showing up without changes in the next version of the language, and even if it doesn't change, it probably won't show up widely in other browsers for a while.

Overview

First-class coroutines, represented as objects encapsulating suspended execution contexts (i.e., function activations). Prior art: Python, Icon, Lua, Scheme, Smalltalk.

Examples

The “infinite” sequence of Fibonacci numbers (notwithstanding behavior around 253):

function* fibonacci() {
    let [prev, curr] = [0, 1];
    for (;;) {
        [prev, curr] = [curr, prev + curr];
        yield curr;
    }
}

Generators can be iterated over in loops:

for (n of fibonacci()) {
    // truncate the sequence at 1000
    if (n > 1000)
        break;
    print(n);
}

Generators are iterators:

let seq = fibonacci();
print(seq.next()); // 1
print(seq.next()); // 2
print(seq.next()); // 3
print(seq.next()); // 5
print(seq.next()); // 8

Painless css3 writing

10 votes

When I want to create a gradient background in css3 I have to do this:

background-color: #3584ba;
background-image: -webkit-gradient(linear, left top, left bottom, from(#54a0ce), to(#3584ba)); /* Safari 4+, Chrome */
background-image: -webkit-linear-gradient(top, #54a0ce, #3584ba); /* Safari 5.1+, Chrome 10+ */
background-image:    -moz-linear-gradient(top, #54a0ce, #3584ba);  /* FF3.6 */
background-image:      -o-linear-gradient(top, #54a0ce, #3584ba); /* Opera 11.10+ */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#54a0ce', endColorstr='#3584ba'); /* IE */

and this is really annoying. Is there a better solution, for example a jquery plugin, that will make my code cross browser compatible, if I just use:

background-image: -webkit-linear-gradient(top, #54a0ce, #3584ba); /* Safari 5.1+, Chrome 10+ */

for example? Is there a tool to help me write css3 code more easy?

There are many tools for this:

These are generally referred to as CSS Preprocessors.

You would end up writing something like this once, like a function definition (usually called a "mixin"):

.linear-gradient(@start, @end) {
    background-color: @end;
    background-image: -webkit-gradient(linear, left top, left bottom, from(@start), to(@end)); /* Safari 4+, Chrome */
    background-image: -webkit-linear-gradient(top, @start, @end); /* Safari 5.1+, Chrome 10+ */
    background-image:    -moz-linear-gradient(top, @start, @end);  /* FF3.6 */
    background-image:      -o-linear-gradient(top, @start, @end); /* Opera 11.10+ */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='@start', endColorstr='@end'); /* IE */
}

Then to apply:

.my-class {
    .linear-gradient(#54a0ce, #3584ba);
}
.my-other-class {
    .linear-gradient(#ccc, #aaa);
}

Highly recommend.

Why does a function declaration override non-writable properties of the global object?

10 votes

Setting a property descriptor like this:

Object.defineProperty(window, 'someFunction', {
    value: function() { alert('safe'); },
    writable: false,
    enumerable: false,
    configurable: false
});

...should, as far as I know, make the someFunction property of window non-writable. It works for function expressions as I expect, whether the function is directly assigned to the object property... fiddle

window.someFunction = function() { alert('boom!'); }
someFunction(); // safe

...or assigned to a global variable: fiddle

var someFunction = function() { alert('boom!'); }
someFunction(); // safe

However, it doesn't seem to work with function declarations: fiddle

function someFunction() { alert('boom!'); }
someFunction(); // boom!

Is this behavior intentional? What is the reasoning behind it? Is this documented anywhere? Or am I just making some kind of silly mistake?


By the way, I'm using Chromium 17 to test this. Strict mode doesn't seem to make any difference.

This is a bug (see Bug #115452), which I also encountered when answering this question.

Compatibility check: Test case

  • In Firefox 4+, it works fine.
  • In Chrome 16, it works fine.
  • In Chrome 17, it does not work.
  • IE8- doesn't have Object.defineProperty, so it doesn't work
  • In IE9, it does not work.
  • In Safari 5, it does not work.

Leap year check using bitwise operators (amazing speed)

10 votes

Someone on JSPerf dropped an amazingly fast implementation for checking leap years of the ISO calendar (link: Odd bit manipulations):

function isLeapYear(year) {
  return !(year & 3 || year & 15 && !(year % 25));
}

Using Node.js, I quickly checked it against two other one-liner implementations I know.

function isLeapClassic(y) { return (y % 4 == 0) && !(y % 100 == 0) || (y % 400 == 0); }
function isLeapXOR(y) { return (y % 4 == 0) ^ (y % 100 == 0) ^ (y % 400 == 0); }
function isLeapBitwise(y) { return !(y & 3 || y & 15 && !(y % 25)); }

//quick'n'dirty test on a small range!
//works with negative integers too
for (var i = 1900; i <= 2100; i++) {
    console.log(
        "year = %d,\t%d%d%d",
        i,
        isLeapClassic(i),
        isLeapXOR(i),
        isLeapBitwise(i)
    );
}

It works as expected, but my problem is I can't figure how. I know ((a % b) == (a & (b-1)) when b is power of two so (year % 4) == (year & 3), but year & 15 && !(year % 25) is quite hard to figure out. Can someone explain me how it works? Any reference about this implementation?

year & 3 is the same as year % 4. Not so tricky there, it just represents the usual 4-year cycle.

year & 15 is the same as year % 16.

So, it's not a leap year if the year doesn't divide evenly by 4, or if it doesn't divide evenly by 16 but does divide evenly by 25. This means that every multiple of 25 is not a leap year unless it's also a multiple of 16. Since 16 and 25 don't have any common factors, the only time both conditions are met is when the year is a multiple of 16*25, or 400 years. The multiples of 4*25 will be considered not leap years, accounting for the 100 year cycle.

1900 wasn't a leap year because it was divisible by 100, 2000 was a leap year because it was divisible by 400, and 2100 won't be a leap year.

Can anyone explain this bizarre JS behavior concerning string concatenation?

10 votes

I just posted this to a gist: https://gist.github.com/2228570

var out = '';

function doWhat(){
    out += '<li>';
    console.log(out === '<li>'); // at this point, out will equal '<li>'
    return '';
}

out += doWhat();
console.log(out, out === '<li>');
// I expect out to == '<li>', but it's actually an empty string!?

This behavior is odd, does anyone have an explanation? This is a tough thing to google. It also makes no difference if you use out += or out = out +.

EDIT: @paislee made a JSFiddle that demonstrates how if doWhat is on a separate line, it behaves as expected: http://jsfiddle.net/paislee/Y4WE8/

It seems you're expecting doWhat to be called before the += is evaluated.

But, the progression of the line is:

out += doWhat();      // original line
out = out + doWhat(); // expand `+=`
out = '' + doWhat();  // evaluate `out`, which is currently an empty string
out = '' + '';        // call `doWhat`, which returns another empty string
out = '';             // result

The out += '<li>'; inside doWhat is updating the variable, but too late to have a lasting effect.

For loop Variations in javascript

10 votes

In this website there are a list of for loop variations. I can understand the usage of for(var i=0, len=arr.length; i<len ;i++) loop (where arr is an array), since the arr.length isnt calculated every step there is marginal performance gain. However what are the advantages of using the other variants? For instance loops like

  1. for (var i=arr.length; i--;)
  2. for (var i=0, each; each = arr[i]; i++)

Are there any noticeable changes in performance by using different for loop variations? I generally use for(var i=0, len=arr.length; i<len ;i++) even for very big arrays. So I just want to know if there is something I am missing out here.

It is widely considered that a reversed while loop

var loop = arr.length;
while( loop-- ) {
}

is the fastest loop-type available in C-like languages (this also applied to ECMAscript for quite a while, but I think all up-to-date engines are pretty even on standard loops today). ( jsperf )

Your 'variations' are actually no variations, but just different usage of the conditional statement within the for-loop (which, actually makes it a variation..doh!). Like

1) for (var i=arr.length; i--;)

Just uses the conditional part from the for-loop to do both, iterating and checking if i has a truthy value. As soon as i becomes 0 the loop will end.

2) for (var i=0, each; each = arr[i]; i++)

Here we get the element from each iteration, so we can directly access that within the loop body. This is commonly used when you are tired of always repeating arr[ n ].

You're doing well in caching the .length property before looping. As you correctly mentioned, it is faster because we don't have to access that property in every iteration. Beyond that, it's also required sometimes in DOM scripting, when dealing with 'live structures' like HTMLCollections.

How to catch exceptions thrown in callbacks passed to jQuery?

9 votes

I'd like to catch exceptions thrown from callbacks passed to jQuery (either to event handlers like click, or to jqXHR methods such as then or always).

I've identified two options:

  • window.onerror handler - this is only a partial solution because it isn't supported on Android which is one of my target platforms
  • handling exceptions within each individual callback - not DRY at all!

The only other thing I can think of is overriding jQuery methods but that can result in problems any time I upgrade jQuery. For AJAX handlers, I could possibly use $.ajaxSetup (per the answer to Exceptions thrown in jQuery AJAX callbacks swallowed?) but I'm not sure that will allow me to catch everything.

Are there any other options?

You can wrap each callback like this:

function cbWrapper(fn) {
    return function() {
        try {
            return(fn.apply(this, arguments));
        } catch(e) {
            // handle all your exceptions here
        }
    };
}

So, when you go to pass a callback to an Ajax call, instead of passing the actual callback, you pass cbWrapper(callback).

$.get(url, cbWrapper(myRealCallback));

Or the inline anonymous version would be like this:

$.get(url, cbWrapper(function() {
    // actual callback code here
}));

A more advanced way of doing it would be to override $.get() with your own implementation that wraps the callback automatically, but that gets tricky because jQuery is so flexible about what arguments are actually passed. Because of that and because you have to override one specific argument to make this work, you would have to duplicate all of their argument detection code that figures out which arguments are present and which correspond to which actual function parameters. That code is a bit messy. It's doable and probably won't break because if jQuery broke it, then existing jQuery code would break, but it isn't very clean.

If it's all your own code, you could just make your own version of $.get() that isn't so flexible with argument positions and switch all of your code to use it instead of the actual $.get():

jQuery.fn.myGet = function(url, fn) {
    return(jQuery.get(url, cbWrapper(fn)));
}

Is jQuery .text() method XSS safe?

9 votes

I have unescaped data from users.

So is it safe to use like this:

var data = '<test>a&f"#</test>'; // example data from ajax response
if (typeof(data) === 'string')
    $('body').text(data);

Can I use like this or there is some problems like encoding or some specific symbols that I should be careful and add more strict validation?

When you set the text of an element using the text method, jQuery uses createTextNode internally, which escapes all special characters.

From the jQuery docs:

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <)

So yes, it should be safe. Here's your example in jsfiddle. Notice how the tags appear as literal text.

Save object states in .data or attr - Performance vs CSS?

9 votes

In response to my answer yesterday about rotating an Image, Jamund told me to use .data() instead of .attr()

First I thought that he is right, but then I thought about a bigger context... Is it always better to use .data() instead of .attr()? I looked in some other posts like what-is-better-data-or-attr or jquery-data-vs-attrdata

The answers were not satisfactory for me...

So I moved on and edited the example by adding CSS. I thought it might be useful to make a different Style on each image if it rotates. My style was the following:

.rp[data-rotate="0"] {
    border:10px solid #FF0000;
}
.rp[data-rotate="90"] {
    border:10px solid #00FF00;
}
.rp[data-rotate="180"] {
    border:10px solid #0000FF;
}
.rp[data-rotate="270"] {
    border:10px solid #00FF00;
}

Because design and coding are often separated, it could be a nice feature to handle this in CSS instead of adding this functionality into JavaScript. Also in my case the data-rotate is like a special state which the image currently has. So in my opinion it make sense to represent it within the DOM.

I also thought this could be a case where it is much better to save with .attr() then with .data(). Never mentioned before in one of the posts I read.

But then i thought about performance. Which function is faster? I built my own test following:

<!DOCTYPE HTML>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function runfirst(dobj,dname){
  console.log("runfirst "+dname);
  console.time(dname+"-attr");
  for(i=0;i<10000;i++){
    dobj.attr("data-test","a"+i);
  }
  console.timeEnd(dname+"-attr");
  console.time(dname+"-data");
  for(i=0;i<10000;i++){
    dobj.data("data-test","a"+i);
  }
  console.timeEnd(dname+"-data");
}
function runlast(dobj,dname){
  console.log("runlast "+dname);
  console.time(dname+"-data");
  for(i=0;i<10000;i++){
    dobj.data("data-test","a"+i);
  }
  console.timeEnd(dname+"-data");
  console.time(dname+"-attr");
  for(i=0;i<10000;i++){
    dobj.attr("data-test","a"+i);
  }
  console.timeEnd(dname+"-attr");  
}
$().ready(function() {
  runfirst($("#rp4"),"#rp4");
  runfirst($("#rp3"),"#rp3");
  runlast($("#rp2"),"#rp2");
  runlast($("#rp1"),"#rp1");
});
</script>
</head>
<body>
    <div id="rp1">Testdiv 1</div>
    <div id="rp2" data-test="1">Testdiv 2</div>
    <div id="rp3">Testdiv 3</div>
    <div id="rp4" data-test="1">Testdiv 4</div>
</body>
</html>

It should also show if there is a difference with a predefined data-test or not.

One result was this:

runfirst #rp4
#rp4-attr: 515ms
#rp4-data: 268ms
runfirst #rp3
#rp3-attr: 505ms
#rp3-data: 264ms
runlast #rp2
#rp2-data: 260ms
#rp2-attr: 521ms
runlast #rp1
#rp1-data: 284ms
#rp1-attr: 525ms

So the .attr() function did always need more time than the .data() function. This is an argument for .data() I thought. Because performance is always an argument!

Then I wanted to post my results here with some questions, and in the act of writing I compared with the questions Stack Overflow showed me (similar titles)

And true enough, there was one interesting post about performance

I read it and run their example. And now I am confused! This test showed that .data() is slower then .attr() !?!! Why is that so?

First I thought it is because of a different jQuery library so I edited it and saved the new one. But the result wasn't changing...

So now my questions to you:

  • Why are there some differences in the performance in these two examples?
  • Would you prefer to use data- HTML5 attributes instead of data, if it represents a state? Although it wouldn't be needed at the time of coding? Why - Why not?

Now depending on the performance:

  • Would performance be an argument for you using .attr() instead of data, if it shows that .attr() is better? Although data is meant to be used for .data()?

UPDATE 1:
I did see that without overhead .data() is much faster. Misinterpreted the data :) But I'm more interested in my second question. :)

Would you prefer to use data- HTML5 attributes instead of data, if it represents a state? Although it wouldn't be needed at the time of coding? Why - Why not?

Are there some other reasons you can think of, to use .attr() and not .data()? e.g. interoperability? because .data() is jquery style and HTML Attributes can be read by all...

UPDATE 2:

As we see from T.J Crowder's speed test in his answer attr is much faster then data! which is again confusing me :) But please! Performance is an argument, but not the highest! So give answers to my other questions please too!

UPDATE 3:

My test seems to be false because of the fire-bug I used while testing! The same file in chrome listed attr faster and a second test on jsperf also says attr is faster

This performance part of the question screams of premature optimization; see below. (Lest you get the wrong idea: I too am frequently guilty of wondering about the same sort of premature optimization question.)

But getting performance out of the way (other points addressed below the graph): As far as I can see, attr is faster than data in jQuery 1.7.1: http://jsperf.com/jquery-setting-attr-vs-data This surprises me. Not that it's remotely likely to matter.

Gratuitous bar graph (longer lines = faster performance):

Gratuitous bar graph from jsperf

Are there some other reasons you can think of, to use .attr() and not .data()?

At least a couple come to mind:

  1. The advantage of data is that it doesn't have to write to the element every time; you only write to the actual element the first time, and from then on jQuery is just updating a value in a JavaScript object it maintains in a separate object cache (connected to the element via a key). (I'm not sure why it's slower than attr; perhaps because of the indirection.)

  2. One thing I dislike about data is that it's not symmetrical: The first time you access data on an element, the data object is seeded with data-* attributes from the element; but from there on out, there is no connection between the two.

    Example (live copy | live source):

    var target = $("#target");
    display("data('foo'): " + target.data("foo"));
    display("data-foo: " + target.attr("data-foo"));
    display("Setting data('foo')");
    target.data("foo", "updated data('foo')");
    display("data('foo'): " + target.data("foo"));
    display("data-foo: " + target.attr("data-foo"));
    display("Setting data-foo");
    target.attr("data-foo", "updated data-foo");
    display("data('foo'): " + target.data("foo"));
    display("data-foo: " + target.attr("data-foo"));
    

    Assuming the #target element starts out with data-foo="bar", the output is:

    data('foo'): bar
    data-foo: bar
    Setting data('foo')
    data('foo'): updated data('foo')
    data-foo: bar
    Setting data-foo
    data('foo'): updated data('foo')
    data-foo: updated data-foo

    That can be confusing and surprising. The way you have to think about it is that the data-* attributes are default values only. I just don't like how they're so dependent on whether you've called data before or not; unless you never write to the data-* attribute directly, you can't be sure what value data will get (the original from the markup, or a value you updated later before you called data). It seems a bit chaotic to me, but if you set yourself rules (never write to data-* attributes directly and only ever use data, for instance), you can avoid the chaos.

  3. When you use attr, you can only store strings. When you use data, you can store any JavaScript value or object reference.


Because performance is always an argument!

Not in 2012. :-) Or at least, it's a lot lower down the list relative to other arguments than it used to be absent a specific, demonstrable performance problem.

Let's look at your runfirst #rp4 results: 10k iterations of attr took 515ms; 10k iterations of data took 268ms. That's 51.5 usec (microseconds, millionths of a second) each vs. 26.8 usec each. So you're wondering whether to use data if it saves you 24.7 usec per operation. Humans perceive things on the order of tenths of seconds. So for it to matter, you have to do this op roughly 4,000 times in a tight loop for a human to notice the difference. That's just not even close to worth worrying about, even in a mousemove handler.

If you're into that kind of territory (4,000/second in a tight loop), you'll probably want to avoid storing the information on the element at all.

socket.io client not receiving messages from server

9 votes

I'm trying to implement a system with two clients one of them sends a message and the other one shall receive it. The figure below will explain it in a more visual way:

socket.io message communication chart

So, the client 1 send the message to the server (and this works), the server receives a "push" message and emits a "pop" message that should be picked up by Client 2. The problem here is that Client 2 never receives the "pop" message. :(

Here's the code for all of them.

SERVER.JS

var app = require('express').createServer()
  , io = require('socket.io').listen(app);

app.listen(999);

app.get('/webclient', function (req, res) {
    res.sendfile(__dirname + '/web.html');
});

app.get('/mobile', function (req, res) {
    res.sendfile(__dirname + '/mobile.html');
});

io.sockets.on('connection', function (socket) {
//      socket.emit('pop', { hello: 'world' });
    socket.on('push', function (data) {
        console.log('push received, emitting a pop');
        socket.emit('pop', { hello: 'world' });
    });
});

CLIENT 1 ( aka mobile.html )

<html>
    <head>
        <title>
            Mobile
        </title>
        <script src="/socket.io/socket.io.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js" type="text/javascript"></script>
        <script>
          var socket = io.connect('http://localhost:999');
        </script>
    </head>
    <body>
        <input type="button" name="act" id="push" value="message" />
        <script type="text/javascript" charset="utf-8">
            window.addEvent('domready', function() {
                $('push').addEvent('click', function() { 
                    socket.emit('push', { hello: 'world' });
                });
            });
        </script>
    </body>
</html>

CLIENT 2 (aka web.html)

<script src  = "/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:999');
  socket.on('pop', function (data) {
    console.log(data);
  });
</script>

I just cannot understand the reason why Client 2 does not receive the "pop" message, I'm quite new to socket.io and node.js in general so some mechanics to me are still a bit obscure, so I apologize in advance for my noobness. :)

cheers

-k-

The function passed to .on is called for each socket to do the initialization (binding events etc), and socket refers to that current socket. This will be client 1 when you receive a push message, because the handler function is bound to the push event of that socket - you bound that function when client 1 connected (where socket refers to client 1).

io.sockets refers to all sockets connected, so including client 2 in your case.

How to avoid custom/Server error in web site?

8 votes

I have asp.net web application located on server I want to avoid all custom and server error from my site.

For that I have used

<customErrors mode="RemoteOnly" defaultRedirect="~/ErrorPage/TryAgainLater.aspx">   <error redirect="~/ErrorPage/PageNotFound.aspx" statusCode="404"/> </customErrors>

Using above code will able avoid some issue. ie.

Suppose "http://Exaple.com/Careers.aspx" Page available in my site then

Case 1. http://Exaple.com/Careersss.aspx "It was working correct as per above rule".

Case 2. http://Exaple.com/!@##Careersss.aspx "Not working" Note : Here I add special character

Case 3: http://Exaple.com/Careersss.aspxxxx "Not working" Note : add character after ".aspx"

case 4: http://Exaple.com/Careersss.aspx/!@!@!@! "Not works design breaking here". Note : Add '/' with special character.

please help me when user get case 2,3,4 then they automatically redirected to error page.

Thanks In advance.

For above problem we have to change IIS Setting please refer :

http://www.braintrove.com/id/46/page/2#Configure-IIS-for-custom-error-pages

http://blogs.msdn.com/b/webtopics/archive/2008/05/28/iis-7-0-http-error-pages.aspx

Techniques for javascript code grouping

8 votes

I have lots of functions and event handlers that are split across multiple javascript files which are included on different pages throughout my site.

For performance reasons I want to combine all of those files into 1 file that is global across the site.

The problem is I will have event handlers called on elements that won't necessarily exist and same function names.

This is an example of a typical javascript file...

$(document).ready(function(){
    $('#blah').keypress(function(e){
        if (e.which == 13) {
            checkMap();
            return false;
        }
    });
});

function checkMap() {
    // code
}

function loadMap() {
    // code
}

I would need to seperate this code into an object that is called on that specific page.

My thoughts are I could re-write it like this:

(function($) {
    $.homepage = {
        checkMap: function(){
            // code
        },
        loadMap: function(){
            //code  
        }
    };
})(jQuery);

And then on the page that requires it I could call $.homepage.checkMap() etc.

But then how would I declare event handlers like document.ready without containing it in it's own function?

Any advice on best practice would be great, thanks!

I think that all you need is a namespace for you application. A namespace is a simple JSON object that could look like this:

var myApp = {
    homepage : {
      showHeader : function(){},
      hideHeader : function(){},
      animationDelay : 3400,
      start : function(){} // the function that start the entire homepage logic
    },
    about : {
    .... 
    }
}

You can split it in more files:

  1. MyApp will contain the myApp = { } object, maybe with some useful utilities like object.create or what have you.
  2. Homepage.js will contain myApp.homepage = { ... } with all the methods of your homepage page.
  3. The list goes on and on with the rest of the pages.

Think of it as packages. You don't need to use $ as the main object.

 <script src="myapp.js"></script>
 <script src="homepage.js"></script>
 <-....->
 <script>
   myApp.homepage.start();
 </script>

Would be the way I would use the homepage object.

When compressing with YUI, you should have:

<script src="scripts.min.js"></script>
<script>
    myApp.homepage.start();
 </script>