Best javascript questions in March 2011

How can you flip website upside down in IE ? (for the April 1st)

27 votes

We are making April 1st prank in our office, and wanted to flip our corporate website upside down for several hours tomorrow :)

My patch works everywhere but not in IE... Can anyone help ?

<script type="text/javascript">
   document.body.style.MozTransform = 'rotate(180deg)';
   document.body.style['-webkit-transform'] = 'rotate(180deg)';
</script>

A slightly simpler version for IE (no matrix stuff):

body {
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
}

14 votes

I've been starting to play around with node.js recently and I've come across a situation where I need a little guidance around the prescriptive node.js way of accomplishing a task. In this particular case I need to create a bunch of directories and, when all of the directories have been created I need to perform some final operation. The order in which the directories are created does not matter, I just need to perform a final operation after the last one is.

The easiest way the accomplish this would be to fall back to the old synchronous habits. That is, just call fs.mkdirSync for each of the directories and perform the operation at the end. For example:

fs.mkdirSync('a', 0755);
fs.mkdirSync('a/b', 0755);
fs.mkdirSync('a/b/c', 0755);
performFinalOperation();

While this would work, it doesn't feel like it's the node.js way of doing it. Obviously, the program would block while it waits for the OS to create the directory and return. On a heavily loaded system with a file system that's mounted remotely each of the mkdirSync calls could take a very long time. So clearly, this isn't the best approach.

One of node.js' main selling points is the fact that it's asynchronous. So the calls to fs.mkdir could be chained through the callbacks:

fs.mkdir('a', 0755, function(e) {
    if (!e) {
        fs.mkdir('a/b', 0755, function(e) {
            if (!e) {
                fs.mkdir('a/b/c', 0755, function(e) {
                    if (!e) {
                        performFinalOperation();
                    }
                });
            }
        });
    }
});

Again, this approach I'm sure works, but it leads to really deep nesting and code duplication. It does have the benefit of not blocking while the directories are created, but at what cost?

Another approach would be to get really fancy in an effort to avoid the code duplication and nesting:

(function (directories) {
    if (directories.length === 0) {
        performFinalOperation();
    } else {
        var tail = arguments.callee;
        fs.mkdir(directories.shift(), 0755, function(e) {
            tail(directories);
        });
    }
})(['a', 'a/b', 'a/b/c']);

This approach makes use of all sorts of crazy stuff: anonymous self calling functions and the magical arguments.callee. But worst of all, it isn't obvious what the code is doing at first glance.

So, while the concrete question is around creating directories I'm more interested in the approach that a seasoned node.js veteran would take when this sort of situation arises. I'm specifically not interested in what libraries are around to make this easier.

Oh, hey Bryan :)

I'm specifically not interested in what libraries are around to make this easier.

The seasoned Node veteran has written at least one of their own control flow libs. We just copied Twisted's Deferred classes since they already did the hard work and research into async programming. This inverts the standard callback-as-argument pattern and I like the resulting code, but if you want to nest a bunch of callbacks you can still do that with Deferred and end up with just as much of a mess.

With the restriction of not using libraries people generally do exactly what you wrote. There really isn't any other choice. Without language changes such as generators the best we can do is use libraries. If you don't want to use an existing one you will end up rolling your own or just writing a lot of boilerplate.

What's the best way to handle longtap and double-tap events on mobile devices using jQuery?

14 votes

I'm looking for the best solution to adding both "doubletap" and "longtap" events for use with jQuery's live(), bind() and trigger(). I rolled my own quick solution, but it's a little buggy. Does anyone have plugins they would recommend, or implentations of their own they'd like to share?

It has been reported to jQuery as a bug, but as doubletapping isn't the same as doubleclicking, it does not have a high priority. However, mastermind Raul Sanchez coded a jquery solution for doubletap which you can probably use! Here's the link, works on mobile Safari.

It's easy to use:

$('selector').doubletap(function() {});

-edit-

And there's a longtap plugin here! You can see a demo on your iPad or iPhone here.

How can I Observe the contents of an 'a' tag - jquery

13 votes

I have a blank <a> tag that content is loaded into via an external piece of javascript. I want to observe the <a> and when its content changes perform another task. The content will only ever change once.

Can this be done?

I am using also using jQuery.

Thanks in advance

You can use a mixture out of jQuery && DOM Level 3 events (see browser support below).

If you want to check for any changes within the content, you could do this:

var $a = $('a');

$a.one('DOMNodeInserted', function(e) {
    console.log('content changed!: ', e);    

    console.log('new content: ', $(this).html());   
});

$a.one('DOMAttrModified', function(e) {
    console.log('attribute changed!: ');        

    console.log('attribute that was changed: ', e.attrName);
});

See this code in action: http://jsfiddle.net/wJbMj/1/

Reference: DOMNodeInserted, DOMAttrModified


While the above solution is actually pretty convinient to me, it'll only work in browser that support those events. To have a more generic solution, you can hook into jQuerys setter methods. The downside in this solution is, that you will only catch changes that were done through jQuery.

var _oldAttr = $.fn.attr;
$.fn.attr = function() {
    console.log('changed attr: ', arguments[0]);
    console.log('new value: ', arguments[1]);
    return _oldAttr.apply(this, arguments);
};

You could hook into .text() and .html() the exact same way. You would need to check if the this value within the overwritten methods represent the correct DOMnode.

Advanced jQuery/Ajax books or tutorials online

13 votes

Hello,

To begin with, I believe I know jquery basics quite well. I want to learn more and be able to make more complex things (like live chat with many features or something like that).

So, can anyone suggest me good jQuery books or tutorials online to help me become really advanced in this field.

I have an idea and I want to make it as optimal and clever as possible.

Thank you very much.



Why do people use jQuery for basic operations?

13 votes

I am a JS programmer and I have been experimenting with jQuery a lot but have run into a couple puzzling aspects.

I feel like people use jQuery for much more than necessary. I really just want to know why picking jQuery may be better than using just pure JS.

I know it makes sense for webfx like the animate and fades but for things like adding event listeners it seems just as easy to use

obj = document.getElementByID(_ID_);
obj.addEventListener("mousedown"...);

An example of this is the answer I found on StackOverflow earlier today about performing an action for highlighted text. jQuery: get the highlighted text

In the example linked in the answer at http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html

The guy uses the bind function to the document. Why use bind rather than addEventListener. Also with jQuery everything needs to be included in the .ready() method how is this better than (or why choose it over)

document.addEventListener('load', function () { ... }, false);

There are other times I have seen jQuery used that puzzled me, I hope you guys can shine some light on it for me.

People use jQuery because it's simpler, easier, and more powerful, and because it helps them forget about IE.

To answer your specific questions:

  1. Otherwise, you need to call attachEvent for IE.
    Also, jQuery event handling has simpler syntax, and supports live events.

  2. jQuery does not require you to put everything in a ready handler; it's actually better to move your code to the bottom of the page and execute it immediately.
    Unlike document.addEventListener('load', ...), jQuery's ready event will not wait for images to load.
    Also, it works in IE, and it will still run your code even if the document already loaded.

Why don't I just build the whole web app in Javascript and Javascript HTML Templates?

12 votes

I'm getting to the point on an app where I need to start caching things, and it got me thinking...

  1. In some parts of the app, I render table rows (jqGrid, slickgrid, etc.) or fancy div rows (like in the New Twitter) by grabbing pure JSON and running it through something like Mustache, jquery.tmpl, etc.
  2. In other parts of the app, I just render the info in pure HTML (server-side HAML templates), and if there's searching/paginating, I just go to a new URL and load a new HTML page.

Now the problem is in caching and maintainability.

On one hand I'm thinking, if everything was built using Javascript HTML Templates, then my app would serve just an HTML layout/shell, and a bunch of JSON. If you look at the Facebook and Twitter HTML source, that's basically what they're doing (95% json/javascript, 5% html). This would make it so my app only needed to cache JSON (pages, actions, and/or records). Which means you'd hit the cache no matter if you were some remote api developer accessing a JSON api, or the strait web app. That is, I don't need 2 caches, one for the JSON, one for the HTML. That seems like it'd cut my cache store down in half, and streamline things a little bit.

On the other hand, I'm thinking, from what I've seen/experienced, generating static HTML server-side, and caching that, seems to be much better performance wise cross-browser; you get the graphics instantly and don't have to wait that split-second for javascript to render it. StackOverflow seems to do everything in plain HTML, so does Google, and you can tell... everything appears at once. Notice how though on twitter.com, the page is blank for .5-1 seconds, and the page chunks in: the javascript has to render the json. The downside with this is that, for anything dynamic (like endless scrolling, or grids), I'd have to create javascript templates anyway... so now I have server-side HAML templates, client-side javascript templates, and a lot more to cache.

My question is, is there any consensus on how to approach this? What are the benefits and drawbacks from your experience of mixing the two versus going 100% with one over the other?

Update:

Some reasons that factor into why I haven't yet made the decision to go with 100% javascript templating are:

  • Performance. Haven't formally tested, but from what I've seen, raw html renders faster and more fluidly than javascript-generated html cross-browser. Plus, I'm not sure how mobile devices handle dynamic html performance-wise.
  • Testing. I have a lot of integration tests that work well with static HTML, so switching to javascript-only would require 1) more focused pure-javascript testing (jasmine), and 2) integrating javascript into capybara integration tests. This is just a matter of time and work, but it's probably significant.
  • Maintenance. Getting rid of HAML. I love HAML, it's so easy to write, it prints pretty HTML... It makes code clean, it makes maintenance easy. Going with javascript, there's nothing as concise.
  • SEO. I know google handles the ajax /#!/path, but haven't grasped how this will affect other search engines and how older browsers handle it. Seems like it'd require a significant setup.

Persistant private data storage.

You need a server to store data with various levels of public/private access. You also need a server for secure closed source information. You need a server to do heavy lifting that you don't want to do on the client. Complex data querying is best left upto your database engine. Indexing and searching is not yet optimised for javascript.

Also you have the issues of older browsers being far slower. If your not running FF4/Chrome or IE9 then there is a big difference between data manipulation and page construction on the client and the server.

I myself am going to be trying to build a web application made entirely using a MVC framework and template's but still using the server to connect to secure and optimised database.

But in general the application can indeed be build entirely in javascript and using templates. The various constructs and javascript engines have advanced enough to do this. There are enough popular frameworks out there to do this. The Pure javascript web applications are no longer experiments and prototypes.

Oh, and if were recommending frameworks for this, then take a look at backbone.js.


Security


Let's not forget that we do not trust the client. We need serverside validation. JavaScript is interpreted, dynamic and can be manipulated at run time. We never trust client input.

How are closures and scopes represented at run time in JavaScript

12 votes

This is mostly an out-of-curiosity question. Consider the following functions

var closure ;
function f0() {
    var x = new BigObject() ;
    var y = 0 ;
    closure = function(){ return 7; } ;
}
function f1() {
    var x = BigObject() ;
    closure =  (function(y) { return function(){return y++;} ; })(0) ;
}
function f2() {
    var x = BigObject() ;
    var y = 0 ;
    closure = function(){ return y++ ; } ;
}

In every case, after the function has been executed, there is (I think) no way to reach x and so the BigObject can be garbage collected, as long as x is the last reference to it. A simple minded interpreter would capture the whole scope chain whenever a function expression is evaluated. (For one thing, you need to do this to make calls to eval work -- example below). A smarter implementation might avoid this in f0 and f1. An even smarter implementation would allow y to be retained, but not x, as is needed for f2 to be efficient.

My question is how do the modern JavaScript engines (JaegerMonkey, V8, etc.) deal with these situations?

Finally, here is an example that shows that variables may need to be retained even if they are never mentioned in the nested function.

var f = (function(x, y){ return function(str) { return eval(str) ; } } )(4, 5) ;
f("1+2") ; // 3
f("x+y") ; // 9
f("x=6") ;
f("x+y") ; // 11

However, there are restrictions that prevent one from sneaking in a call to eval in ways that might be missed by the compiler.

It's not true that there are restrictions that prevent you from calling eval that would be missed by static-analysis: it's just that such references to to eval run in the global scope. Note that this is a change in ES5 from ES3 where indirect and direct references to eval both ran in the local scope, and as such, I'm unsure whether anything actually does any optimizations based upon this fact.

An obvious way to test this is to make BigObject be a really big object, and force a gc after running f0–f2. (Because, hey, as much as I think I know the answer, testing is always better!)

So…

The test

var closure;
function BigObject() {
  var a = '';
  for (var i = 0; i <= 0xFFFF; i++) a += String.fromCharCode(i);
  return new String(a); // Turn this into an actual object
}
function f0() {
  var x = new BigObject();
  var y = 0;
  closure = function(){ return 7; };
}
function f1() {
  var x = new BigObject();
  closure =  (function(y) { return function(){return y++;}; })(0);
}
function f2() {
  var x = new BigObject();
  var y = 0;
  closure = function(){ return y++; };
}
function f3() {
  var x = new BigObject();
  var y = 0;
  closure = eval("(function(){ return 7; })"); // direct eval
}
function f4() {
  var x = new BigObject();
  var y = 0;
  closure = (1,eval)("(function(){ return 7; })"); // indirect eval (evaluates in global scope)
}
function f5() {
  var x = new BigObject();
  var y = 0;
  closure = (function(){ return eval("(function(){ return 7; })"); })();
}
function f6() {
  var x = new BigObject();
  var y = 0;
  closure = function(){ return eval("(function(){ return 7; })"); };
}
function f7() {
  var x = new BigObject();
  var y = 0;
  closure = (function(){ return (1,eval)("(function(){ return 7; })"); })();
}
function f8() {
  var x = new BigObject();
  var y = 0;
  closure = function(){ return (1,eval)("(function(){ return 7; })"); };
}
function f9() {
  var x = new BigObject();
  var y = 0;
  closure = new Function("return 7;"); // creates function in global scope
}

I've added tests for eval/Function, seeming these are also interesting cases. The different between f5/f6 is interesting, because f5 is really just identical to f3, given what is really an identical function for closure; f6 merely returns something that once evaluated gives that, and as the eval hasn't yet been evaluated, the compiler can't know that there is no reference to x within it.

SpiderMonkey

js> gc();
"before 73728, after 69632, break 01d91000\n"
js> f0();
js> gc(); 
"before 6455296, after 73728, break 01d91000\n"
js> f1(); 
js> gc(); 
"before 6455296, after 77824, break 01d91000\n"
js> f2(); 
js> gc(); 
"before 6455296, after 77824, break 01d91000\n"
js> f3(); 
js> gc(); 
"before 6455296, after 6455296, break 01db1000\n"
js> f4(); 
js> gc(); 
"before 12828672, after 73728, break 01da2000\n"
js> f5(); 
js> gc(); 
"before 6455296, after 6455296, break 01da2000\n"
js> f6(); 
js> gc(); 
"before 12828672, after 6467584, break 01da2000\n"
js> f7(); 
js> gc(); 
"before 12828672, after 73728, break 01da2000\n"
js> f8(); 
js> gc(); 
"before 6455296, after 73728, break 01da2000\n"
js> f9(); 
js> gc(); 
"before 6455296, after 73728, break 01da2000\n"

SpiderMonkey appears to GC "x" on everything except f3, f5, and f6.

It appears to as much as possible (i.e., when possible, y, as well as x) unless there is direct eval call within the scope-chain of any function that still exists. (Even if that function object itself has been GC'd and no longer exists, as is the case in f5, which theoretically means that it could GC x/y.)

V8

gsnedders@dolores:~$ v8 --expose-gc --trace_gc --shell foo.js
V8 version 3.0.7
> gc();
Mark-sweep 0.8 -> 0.7 MB, 1 ms.
> f0();
Scavenge 1.7 -> 1.7 MB, 2 ms.
Scavenge 2.4 -> 2.4 MB, 2 ms.
Scavenge 3.9 -> 3.9 MB, 4 ms.
> gc();   
Mark-sweep 5.2 -> 0.7 MB, 3 ms.
> f1();
Scavenge 4.7 -> 4.7 MB, 9 ms.
> gc();
Mark-sweep 5.2 -> 0.7 MB, 3 ms.
> f2();
Scavenge 4.8 -> 4.8 MB, 6 ms.
> gc();
Mark-sweep 5.3 -> 0.8 MB, 3 ms.
> f3();
> gc();
Mark-sweep 5.3 -> 5.2 MB, 17 ms.
> f4();
> gc();
Mark-sweep 9.7 -> 0.7 MB, 5 ms.
> f5();
> gc();
Mark-sweep 5.3 -> 5.2 MB, 12 ms.
> f6();
> gc();
Mark-sweep 9.7 -> 5.2 MB, 14 ms.
> f7();
> gc();
Mark-sweep 9.7 -> 0.7 MB, 5 ms.
> f8();
> gc();
Mark-sweep 5.2 -> 0.7 MB, 2 ms.
> f9();
> gc();
Mark-sweep 5.2 -> 0.7 MB, 2 ms.

V8 appears to GC x on everything apart from f3, f5, and f6. This is identical to SpiderMonkey, see analysis above. (Note however that the numbers aren't detailed enough to tell whether y is being GC'd when x is not, I've not bothered to investigate this.)

Carakan

I'm not going to bother running this again, but needless to say behaviour is identical to SpiderMonkey and V8. Harder to test without a JS shell, but doable with time.

JSC (Nitro) and Chakra

Building JSC is a pain on Linux, and Chakra doesn't run on Linux. I believe JSC has the same behaviour to the above engines, and I'd be surprised if Chakra didn't have too. (Doing anything better quickly becomes very complex, doing anything worse, well, you'd almost never be doing GC and have serious memory issues…)

What blocks Ruby, Python to get Javascript V8 speed?

11 votes

Are there any Ruby / Python features that are blocking implementation of optimizations (e.g. inline caching) V8 engine has?

Python is co-developed by Google guys so it shouldn't be blocked by software patents.

Or this is rather matter of resources put into the V8 project by Google.

What blocks Ruby, Python to get Javascript V8 speed?

Nothing.

Well, okay: money. (And time, people, resources, but if you have money, you can buy those.)

V8 has a team of brilliant, highly-specialized, highly-experienced (and thus highly-paid) engineers working on it, that have decades of experience (I'm talking individually – collectively it's more like centuries) in creating high-performance execution engines for dynamic OO languages. They are basically the same people who also created the Sun HotSpot JVM (among many others).

Lars Bak, the lead developer, has been literally working on V8 for 25 years, which is basically his entire (professional) life (and V8's, too). Some of the people writing Ruby VMs aren't even 25 years old.

Are there any Ruby / Python features that are blocking implementation of optimizations (e.g. inline caching) V8 engine has?

Given that at least IronRuby, JRuby, MagLev, MacRuby and Rubinius have either monomorphic (IronRuby) or polymorphic inline caching, the answer is obviously no.

Modern Ruby implementations already do a great deal of optimizations. For example, for certain operations, Rubinius's Hash class is faster than YARV's. Now, this doesn't sound terribly exciting until you realize that Rubinius's Hash class is implemented in 100% pure Ruby, while YARV's is implemented in 100% hand-optimized C.

So, at least in some cases, Rubinius can generate better code than GCC!

Or this is rather matter of resources put into the V8 project by Google.

Yes. Not just Google. V8 is 25 years old now. The people who are working on V8 also created the Self VM (to this day one of the fastest dynamic OO language execution engines ever created), the Animorphic Smalltalk VM (to this day one of the fastest Smalltalk execution engines ever created), the HotSpot JVM (the fastest JVM ever created, probably the fastest VM period) and OOVM (one of the most efficient Smalltalk VMs ever created).

In fact, Lars Bak, the lead developer of V8, worked on every single one of those, plus a few others.

How to disable resizable property of TextArea?

11 votes

I want to disable the resizable property of a TextArea.

Currently, I can resize a TextArea by clicking on the bottom right corner of the TextArea and dragging the mouse. Is it possible to disable this? Thanks in advance.

Use the following CSS rule to disable this behavior for all TextArea elements:

textarea {
    resize: none;
}

If you want to disable it for some (but not all) TextArea elements, you have a couple of options (thanks to this page).

To disable a specific TextArea with the name attribute set to foo (i.e., <TextArea name="foo"></TextArea>):

textarea[name=foo] {
    resize: none;
}

Or, using an ID (i.e., <TextArea id="foo"></TextArea>):

#foo {
    resize: none;
}

Note that this is only relevant for WebKit-based browsers (i.e., Safari and Chrome), which add the resize handle to TextArea controls.

Firefox 4 onBeforeUnload custom message

11 votes

In Firefox 3, I was able to write a custom confirmation popup with:

window.onbeforeunload = function() {
   if (someCondition) {
      return 'Your stream will be turned off';
   }
}

Now in Firefox 4, it does not show my custom message. The default message that it provides is not even accurate to what my application does.

firefox 4 confirm

Can this default message be overridden?

From MDN:

Note that in Firefox 4 and later the returned string is not displayed to the user. See Bug 588292.

This "Bug" is actually a (imho questionable) feature.. so there's no way to display the message in Firefox 4. If you think it should be changed, comment on that bug so the Firefox developers will know that people actually want to be able to show a custom string.

jQuery .css() function not returning expected values

11 votes

Alright, I've search the jQuery docs (needs somebody devoted to maintaining), I've searched SO, and I've searched Google. I can't find the answer to this question.


In Words

In the past, I remember jQuery working like this:

$('#myObj').width() returns the computed width of #myObj.
$('#myObj').css('width') returns the width as it is entered into the CSS stylesheet.

Now, any jQuery package I use returns the exact same number no matter which method I use.

$('#myObj').width() returns the computed width of #myObj as an integer (float?).
$('#myObj').css('width') returns the computed width of #myObj as a string with px on the end.


In Pseudocode

#myobject{
    width: 14em;
    height: 14em;
}

<div id="myobject">Has Text</div>

<script type="text/javascript">
    $( '#myobject' ).click(function(){
        alert($(this).css('width') + "\n" + $(this).width());
    });
</script>

//Always alerts "224px [newline] 224"
//Expected to alert "14em [newline] 224"

These pixel-based return values are almost completely useless, as I need to do calculations based on what's actually in the CSS. For example, I want to do math on the left position of an element, but I can't because it keeps returning pixel values, which are worthless in an em-based design.

Is there any way to get the actual values out of the CSS in jQuery?
Is this a jQuery bug, or am I missing something?

Here's a jsfiddle: http://jsfiddle.net/yAnFL/1/.


Resolution

Apparently, this is the intended result.
I have decided to use this plugin to do conversions for me.
Taking away control of CSS seems like a poor choice in the jQuery design.

This is not a complete answer to your question but it may be a working solution to caclulate the em values. I adapted this function from here. And here is the updated fiddle.

$.fn.emWidth = function(){
    var wpx = this.width();
    var temp = $('<div />').css({
        width:'1em', 
        position: 'absolute'
    });
    this.append(temp);
    var oneEm = temp.width();
    temp.remove();
    var value = wpx/oneEm;
    return Math.round(value*100)/100;
};

Are there tools / techniques to debug jQuery event handlers?

10 votes

I am currently trying to figure out what click event handlers have attached to my div. There should only be one handler attached, but there appears to be at least one. I'm using FireBug but Chrome could be an option as well. I don't like IE so I'd prefer not to use that.

The best case scenario is that I can inspect my div using FireBug, and see a list of event handlers.

Visual Event is a nice javascript bookmark you can run on a page to see all the events that are attached to a control.

javascript functions and arguments object, is there a cost involved

10 votes

It is common place to see code like that around the web and in frameworks:

var args = Array.prototype.slice.call(arguments);

In doing so, you convert the arguments Object into a real Array (as much as JS has real arrays anyway) and it allows for whatever array methods you have in your Array prototypes to be applied to it, etc etc.

I remember reading somewhere that accessing the arguments Object directly can be significantly slower than an array version of it. Is there any truth to that and under what circumstances / browsers does it incur a performance penalty to do so? Any articles on the subject you know of?

Cheers

update interesting find from http://bonsaiden.github.com/JavaScript-Garden/#function.arguments that invalidates what I read previously... Hoping the question gets some more answers from the likes of @Ivo Wetzel who wrote this.

At the bottom of that section it says:

Performance myths and truths

The arguments object is always created with the only two exceptions being the cases where it is declared as a name inside of a function or one of its formal parameters. It does not matter whether it is used or not.

this goes in conflict with http://www.jspatterns.com/arguments-considered-harmful/, which states:

However, it's not a good idea to use arguments for the reasons of :

  • performance
  • security

The arguments object is not automatically created every time the function is called, the JavaScript engine will only create it on-demand, if it's used. And that creation is not free in terms of performance. The difference between using arguments vs. not using it could be anywhere between 1.5 times to 4 times slower, depending on the browser

clearly, can't both be correct, so which one is it?

ECMA die-hard Dmitrty Soshnikov said:

Which exactly “JavaScript engine” is meant? Where did you get this exact info? Although, it can be true in some implementations (yep, it’s the good optimization as all needed info about the context is available on parsing the code, so there’s no need to create arguments object if it was not found on parsing), but as you know ECMA-262-3 statements, that arguments object is created each time on entering the execution context.

Here's some q&d testing. Using predefined arguments seems to be the fastest, but it's not always feasible to do this. If the arity of the function is unknown beforehand (so, if a function can or must receive a variable amount of arguments), I think calling Array.prototype.slice once would be the most efficient way, because in that case the performance loss of using the arguments object is the most minimal.

Java-esque OOP in JavaScript and a jQuery fail

10 votes

I'm working on a project and I'm really trying to write object-oriented JavaScript code. I have just started reading Douglas Crockford's JavaScript: The Good Parts and I'm quickly beginning to realize that writing Java-esque OOP in JavaScript will be a difficult task.

Thus far, I've written something like the following...

// index.html
$(document).ready(function() {

   $().SetUpElements();
});

// this is in a different js file
$.fn.SetUpElements = function() {

    // do stuff here
    $().UpdateElement();
};

// this is in yet another different js file
$.fn.UpdateElement = function() {

   // do stuff here
   var element = new Element(id, name); // continue doing work
};

function Element(id, name) {

   var id = id;
   var name = name;

   // other stuff
};

... the idea being that I want objects/functions to be refactored and decoupled as much as possible; I want to reuse as much code as I can. I've spread a lot of my code across different .js files with the intention of grouping specific relevant code together, much like if you would write different classes in Java.

As I've been learning more about jQuery, I realized that the notation $.fn.foo = function() { ... }; is actually adding this foo function to the prototype of all jQuery objects. Is this something I should be doing? Am I misusing jQuery somehow?

I would appreciate suggestions on how to improve my approach to OOP in JavaScript and I would love to see references to sources/tutorials/articles/etc... that discuss this topic. Please feel free to provide feedback even if an answer has been selected. I am looking for your advice... this is why I posted :)

Much appreciated, Hristo

** Note: I'm not developing a jQuery plugin. I'm developing a web app and heavily making use of jQuery.

I would say the first way you're creating methods is a misuse of jQuery. The jQuery.fn.foo syntax is generally reserved for functions that act upon a DOM element but you're using them as static functions, by using an empty jQuery object.

If you want to create static functions under the jQuery namespace, you can do:

jQuery.foo = function(){};

then call it via:

jQuery.foo();

instead of:

jQuery.fn.foo = function(){};

which allows you to do:

jQuery('#someElementId').foo();

In terms of OOP. there are many different approaches (module pattern, prototype, factory...). The way I generally approach it, is create a Class as a static function, then invoking it with the keyword new

(function($){
    var undefined;

    $.ClassName = function(options){
        var self = this;
        var cfg = $.extend(true, {}, this.defaults, options);

        // ********************
        // start:private
        // ********************
        function _init(){

        };

        // ********************
        // start:public
        // ********************
        this.methodName = function(){

        };

        _init();
    };

    $.ClassName.prototype.defaults = {};
})(jQuery);

In terms of reusing functionality, there's a threshold after which decoupling is more detrimental than anything. Make sure you keep the right balance of modularity and organization.

Coding Style Guide for node.js apps?

10 votes

Is there a (or several) coding style guide for node.js? If not, what are the emerging styles used by the top open-source node projects?

I'm looking for a guide (or several guides) along the lines of PEP 8, the canonical Coding Style Guide for Python. I've seen various JavaScript guides not worth linking here (mostly old and targeted at client-side JavaScript). I found one interesting node.js style guide.

A coding style guide, or coding conventions, should include (but is not limited to):

  • Code layout: indentation (2 spaces, 4 spaces, tabs, ...), newlines, line breaks, etc.
  • Whitespace, e.g., "function (arg)" vs. "function(arg)"
  • Semicolon or no semicolon, var declaration, ...
  • Naming, e.g., do_this() vs. doThis(), var_name vs. varName, ...
  • node.js and JavaScript idioms, e.g., == vs. ===, callback's first arg is an error object, ...
  • Comments and documentation
  • Accompanying tools, like lint checker, unit test framework, ...

This topic obviously is highly subjective, but I think it's an important step of a community to establish a common and widely accepted coding style in the process of getting mature. Also, it's not all just about taste. In particular, rules like "use === instead of ==" have a direct influence on code quality.

I'd review the coding standards checked by JSLint or look at the author of NPM (Isaac Shlueter's) coding standards.

You could also look at the style used by notable Node.JS coders:

I'll throw mine in there for good measure ;)

Edit: Suggestions from @alienhard

IMO there's a few golden rules you should follow:

  • Never use with or eval
  • Use === over ==
  • Always declare your variables with var in the appropriate scope - don't fallback to the global scope
  • Wrap your app in a closure (function(){})() if you plan on releasing code that runs server-side as well as in the browser
  • Callbacks should take err as the first argument and if they themselves take a callback as an argument, it should be last, e.g. callback(err, param1, param2, callback)

Indentation, spacing between braces and keywords and semicolon placement are all a matter of preference.

JavaScript `new Array(n)` and `Array.prototype.map` weirdness

10 votes

I've observed this in Firefox-3.5.7/Firebug-1.5.3 and Firefox-3.6.16/Firebug-1.6.2

When I fire up Firebug:

    >>> x = new Array(3)
    [undefined, undefined, undefined]
    >>> y = [undefined, undefined, undefined]
    [undefined, undefined, undefined]

    >>> x.constructor == y.constructor
    true

    >>> x.map(function(){ return 0; })
    [undefined, undefined, undefined]
    >>> y.map(function(){ return 0; })
    [0, 0, 0]

What's going on here? Is this a bug, or am I misunderstanding how to use new Array(3)?

It appears that the first example

x = new Array(3);

Creates an array with undefined pointers.

y = [undefined, undefined, undefined]

And the second creates an array with pointers to 3 undefined objects, in this case the pointers them self are NOT undefined, only the objects they point to.

As map is run in the context of the objects in the array I believe the first map fails to run the function at all while the second manages to run.

jQuery Masonry from bottom up

9 votes

Does anyone know how to make jQuery masonry stack from the bottom up? I wrote some rudimentary JS to stack things from bottom up but it couldn't do masonryish stuff like stacking the next brick on the shortest column and bricks that span multiple columns. Since I'm not good with Math, looking at the source code just makes me dizzy.

Stacking from bottom up

Anyone want to try?

You're going to laugh at how easy this is to do, but you will need to modify the plugin (demo).

Basically, I changed line 82 - 85 from this (all that needed changing was top to bottom but I added both so you can switch back and forth):

    var position = {
      left: props.colW * shortCol + props.posLeft,
      top: minimumY
    };

to this:

    var position = (opts.fromBottom) ? {
      left: props.colW * shortCol + props.posLeft,
      bottom: minimumY
    } : {
      left: props.colW * shortCol + props.posLeft,
      top: minimumY
    };

Then added the option in the defaults:

  // Default plugin options
  $.fn.masonry.defaults = {
    singleMode: false,
    columnWidth: undefined,
    itemSelector: undefined,
    appendedContent: undefined,
    fromBottom: false, // new option
    saveOptions: true,
    resizeable: true,
    animate: false,
    animationOptions: {}
  };

Now you can just use the plugin like this:

$('#masonry').masonry({ fromBottom: true });

Update: I also forked the repository on github, so you can just download the changes if you don't want to do them yourself.

What are the pros and cons of adding <script> and <link> elements using JavaScript?

9 votes

Recently I saw some HTML with only a single <script> element in its <head>...

<head>
    <title>Example</title>
    <script src="script.js" type="text/javascript"></script>
    <link href="plain.css" type="text/css" rel="stylesheet" />
</head>

This script.js then adds any other necessary <script> elements and <link> elements to the document using document.write(...): (or it could use document.createElement(...) etc)

document.write("<link href=\"javascript-enabled.css\" type=\"text/css\" rel=\"styleshet\" />");
document.write("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js\" type=\"text/javascript\"></script>");
document.write("<script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js\" type=\"text/javascript\"></script>");
document.write("<link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/trontastic/jquery-ui.css\" type=\"text/css\" rel=\"stylesheet\" />")
document.write("<script src=\"validation.js\" type=\"text/css\"></script>")

Note that there is a plain.css CSS file in the document <head> and script.js just adds any and all CSS and JavaScript which would be used by a JS-enabled user agent.

What are some of the pros and cons of this technique?

The blocking nature of document.write

document.write will pause everything that the browser is working on the page (including parsing). It is highly recommended to avoid because of this blocking behavior. The browser has no way of knowing what you're going to shuff into the HTML text stream at that point, or whether the write will totally trash everything on the DOM tree, so it has to stop until you're finished.

Essentially, loading scrips this way will force the browser to stop parsing HTML. If your script is in-line, then the browser will also execute those scripts before it goes on. Therefore, as a side-note, it is always recommended that you defer loading scripts until after your page is parsed and you've shown a reasonable UI to the user.

If your scripts are loaded from separate files in the "src" attribute, then the scripts may not be consistently executed across all browsers.

Losing browser speed optimizations and predictability

This way, you lose a lot of the performance optimizations made by modern browsers. Also, when your scripts execute may be unpredictable.

For example, some browsers will execute the scripts right after you "write" them. In such cases, you lose parallel downloads of scripts (because the browser doesn't see the second script tag until it has downloaded and executed the first). You lose parallel downloads of scripts and stylesheets and other resources (many browsers can download resources, stylesheets and scripts all at the same time).

Some browsers defer the scripts until after the end to execute them.

The browser cannot continue to parse the HTML while document.write is going on and, in certain cases, when the scripts written are being executed due to the blocking behavior of document.write, so your page shows up much slower.

In other words, your site has just become as slow as it was loading on a decades-old browser with no optimizations.

Why would somebody do it like this?

The reason you may want to use something like this is usually for maintainability. For instance, you may have a huge site with thousands of pages, each loading the same set of scripts and stylesheets. However, when you add a script file, you don't want to edit thousands of HTML files to add the script tags. This is particularly troublesome when loading JavaScript libraries (e.g. Dojo or jQuery) -- you have to change each HTML page when you upgrade to the next version.

The problem is that JavaScript doesn't have an @include or @import statement for you to include other files.

Some solutions

The solution to this is probably not by injecting scripts via document.write, but by:

  1. Using @import directives in stylesheets
  2. Using a server scripting language (e.g. PHP) to manage your "master page" and to generate all other pages (however, if you can't use this and must maintain many HTML pages individually, this is not a solution)
  3. Avoid document.write, but load the JavaScript files via XHR, then eval() them -- this may have security concerns though
  4. Use a JavaScript Library (e.g. Dojo) that has module-loading features so that you can keep a master JS file which loads other files. You won't be able to avoid having to update the version numbers of the library file though...

Ajax Security (i hope)

9 votes

Hi guys, I'm building a browser game and im using a heavy amount of ajax instead of page refreshs. I'm using php and javascript. After alot of work i noticed that ajax isnt exactly secure. The threats im worried about is say someone wants to look up someones information on my SQL server they'd just need to key in right information to my .php file associated with my ajax calls. I was using GET style ajax calls which was a bad idea. Anyways after alot of research i have the following security measures in place. I switched to POST (which isnt really any more secure but its a minor deterent). I have a referred in place as well which again can be faked but again its another deterrent.

The final measure i have in place and is the focus of this question, when my website is loaded i have a 80 char hex key generated and saved in the session, and when im sending the ajax call i am also sending the challenge key in the form of

challenge= <?php $_SESSION["challenge"]; ?>

now when the ajax php file reads this it checks to see if the sent challenge matchs the session challenge. Now this by itself wouldnt do much because you can simply open up firebug and see what challenge is being sent easily. So what I'm having it do is once that challenge is used it generates a new one in the session.

So my question is how secure is this from where im standing it looks one could only see what the challenge key was after it was sent and then it renews and they couldnt see it again until it is sent, making it not possible to send a faked request from another source. So does anyone see any loop hole to this security method or have any addition thoughts or ideas.

See the answer by 'meagar'.

I'd like to mention:

By passing around an identifier in Session, you're doing what the Session is already doing. There's usually a cookie with a unique identifier similar to the one you're generating, which is telling your application, essentially, who that person is. This is how PHP sessions work, in general.

What you would need to do, in this case, is check that for a given request - POST or GET - that the particular user (whose unique user ID, or similar, is stored in the Session) has permission to add/change/delete/whatever with that particular request.

So for a "search" request, you would only return results that User X has permission to view. That way, you don't worry about what they send - if the user doesn't have permission to do something, the system knows not to let them do it.

Hence "you should be authenticating all requests".

Someone feel free to add to this.