Best javascript questions in July 2011

Why does Google +1 record my mouse movements?

129 votes

This is only on pages with a Google +1 box on my website:

enter image description here

It seems to be firing off an event on every mouse move. Anyone know what it is doing? I searched on Google (perhaps I should try Bing for once on this one!) but no one seems to have written about it. Is it recording information about my visitors browsing habits? Is it some sort of CAPTCHA to detect human like behviour?

Example URL, press F12 in chrome, go to timeline and press record, then move your mouse around this page (it plus ones this question, don't worry):

https://plusone.google.com/u/0/_/+1/button?hl=en-US&jsh=r%3Bgc%2F22224365-adc8a19e#url=http://stackoverflow.com/questions/6667544/google-1-recording-mouse-move&size=tall&count=true&id=I1_1310488711647&parent=https://plusone.google.com/u/0/_/+1/button?hl=en-US&jsh=r%3Bgc%2F22224365-adc8a19e#url=http://stackoverflow.com/questions/6667544/google-1-recording-mouse-move&size=tall&count=true&id=I1_1310488711647

For what it's worth (I can see this is going to be a popular question), I don't think there is anything sinister behind it, it might even be a useless artifact/bug, but if it is doing some sort of tracking, well, it seems a little deceptive to me.

Google +1 privacy policy

http://www.google.com/intl/en/privacy/plusone/

Google +1 Button Privacy Policy

June 28, 2011

The Google Privacy Policy describes how we treat personal information when you use Google’s products and services, including information provided when you use the Google +1 button. In addition, the following describes our additional privacy practices specific to your use of the +1 button.

Information we collect and how it is shared

The Google +1 button is a way for you to share information publicly with the world. The Google +1 button helps you and others receive personalized content from Google and our partners. The fact that you +1’d something will be recorded by Google, along with information about the page you were viewing when you clicked on the +1 button. Your +1’s may appear to others as an annotation with your profile name and photo in Google services (such as in search results or on your Google Profile) or elsewhere on websites and ads on the Internet.

We will record information about your +1 activity in order to provide you and other users with a better experience on Google services.

In order to use the Google +1 button, you need to have a public Google Profile visible to the world, which at a minimum includes the name you chose for the profile. That name will be used across Google services and in some cases it may replace another name you’ve used when sharing content under your Google Account. We may display your Google Profile identity to people who have your email address or other identifying information.

Use of the collected information

In addition to the above-described uses, the information you provide to us is used subject to our main Google Privacy Policy.

We may share aggregate statistics related to users’ +1 activity with the public, our users, and partners, such as publishers, advertisers, or connected sites. For example, we may tell a publisher that “10% of the people who +1’d this page are in Tacoma, Washington.”

Your choices

You may view the list of items you have +1’d on the +1 tab on your Profile. You can remove individual items from that list.

You may opt out of seeing +1 recommendations on third-party websites (including on ads on third-party sites) from people you know.

We will store data (such as your recent +1’s) locally in your browser. You may be able to access and clear this information in your browser settings.

More information

Google adheres to the U.S. Safe Harbor privacy principles. For more information about the Safe Harbor framework or our registration, see the Department of Commerce’s website.

Edit

Adding a 500 rep bounty if anyone can work out why and/or what they are collecting.

It appears to be seeding a random number generator with your mouse movements.

The mouse move handler itself does something along the lines of the following:

var b = ((event.X << 16) + event.Y) * (new Date().getTime() % 1000000);
c = c * b % d;
if (previousMouseMoveHandler) previousMouseMoveHandler.call(arguments);

d is (screen.width * screen.width + screen.height) * 1000000, and c is a variable that starts out as 1.

All of this is wrapped in the scope of an anonymous function, which itself is immediately evaluated to return a function that is assigned to a property named "random". That returned function looks something like this:

var b = c;
b += parseInt(hash.substr(0,20), 16);
hash = MD5(hash);
return b / (d + Math.pow(16, 20));

hash, BTW, is a variable that starts out as the MD5 hash of the page's cookies, location, the new Date().getTime(), and Math.random().

(Note, of course, that Google may change the script returned at any time and hence invalidate this analysis)

Convert RGB-->RGBA

93 votes

I have a hex color, e.g. #F4F8FB (or rgb(244, 248, 251)) that I want converted into an as-transparent-as-possible rgba color (when displayed over white). Make sense? I'm looking for an algorithm, or at least idea of an algorithm for how to do so.

For Example:

rgb( 128, 128, 255 ) --> rgba(   0,   0, 255,  .5 )
rgb( 152, 177, 202 ) --> rgba(  50, 100, 150,  .5 ) // can be better(lower alpha)

Ideas?


FYI solution based on Guffa's answer:

function RGBtoRGBA(r, g, b){
    if((g==void 0) && (typeof r == 'string')){
        r = r.replace(/^\s*#|\s*$/g, '');
        if(r.length == 3){
            r = r.replace(/(.)/g, '$1$1');
        }
        g = parseInt(r.substr(2, 2), 16);
        b = parseInt(r.substr(4, 2), 16);
        r = parseInt(r.substr(0, 2), 16);
    }

    var min, a = ( 255 - (min = Math.min(r, g, b)) ) / 255;

    return {
        r    : r = 0|( r - min ) / a,
        g    : g = 0|( g - min ) / a,
        b    : b = 0|( b - min ) / a,
        a    : a = (0|1000*a)/1000,
        rgba : 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')'
    };
}

RGBtoRGBA(204, 153, 102) == RGBtoRGBA('#CC9966') == RGBtoRGBA('C96') == 
    {
       r    : 170,
       g    : 85 ,
       b    : 0  ,
       a    : 0.6,
       rgba : 'rgba(170, 85, 0, 0.6)' 
    }

Take the lowest color component, and convert that to an alpha value. Then scale the color components by subtracting the lowest, and dividing by the alpha value.

Example:

152 converts to an alpha value of (255 - 152) / 255 ~ 0.404

152 scales using (152 - 152) / 0.404 = 0
177 scales using (177 - 152) / 0.404 ~ 62
202 scales using (202 - 152) / 0.404 ~ 123

So, rgb(152, 177, 202) displays as rgba(0, 62, 123, .404).

I have verified in Photoshop that the colors actually match perfectly.

Chrome thinks 99,999 is drastically different than 100,000

26 votes

I just ran into a very interesting issue when someone posted a jsperf benchmark that conflicted with a previous, nearly identical, benchmark I ran.

Chrome does something drastically different between these two lines:

new Array(99999);  // jsperf ~50,000 ops/sec
new Array(100000); // jsperf ~1,700,000 ops/sec

benchmarks: http://jsperf.com/newarrayassign/2

I was wondering if anyone has any clue as to what's going on here!

(To clarify, I'm looking for some low-level details on the V8 internals, such as it's using a different data structure with one vs the other and what those structures are)

Just because this sounded pretty interesting, I searched through the V8 codebase for a static defined as 100000, and I found this kInitialMaxFastElementArray var, which is the subsequently used in the builtin ArrayCodeGeneric function function. While I'm not a c programmer and don't know the nitty-gritty here, you can see that it's using an if loop to determine if it's smaller than 100,000, and returning at different points based on that.

What happens in JavaScript when an AJAX call returns while the script is executing?

24 votes

Suppose I write some JavaScript that performs an AJAX call with myCallback as a callback method to execute when the AJAX succeeds.

Suppose then that some other JavaScript method called myFunction is being invoked on my page when myCallback is invoked asynchronously.

Does one operation take precedence over the other? Do they both run at the same time? What happens?

Suppose then that some other JavaScript method called myFunction is being invoked on my page when myCallback is invoked asynchronously.

Does one operation take precedence over the other? Do they both run at the same time? What happens?

JavaScript on browsers is single-threaded (barring your using web workers, and the syntax for that is explicit). So myFunction will run until it returns — with certain caveats (keep reading). If the ajax layer completes an operation while myFunction is running (which it very well may) and needs to invoke the callback, that call gets queued. The next time your code yields, the next call in the queue will be triggered.

It might seem, then, that we never have to worry about race conditions. That's mostly true, but there are subtleties. For instance, consider this code:

var img = document.createElement('img');
img.src = /* ...the URL of the image... */;
img.onload = function() {
    // Handle the fact the image loaded
    foo();
};
doSomethingElse();
doYetAnotherThing();

Since JavaScript on browsers is single-threaded, I'm guaranteed to get the load event when the image loads, right?

Wrong.

The JavaScript code is single-threaded, but the rest of the environment probably isn't. So it can happen that, having set the img.src, the browser may see that it has a cached copy of the image it can use, and so it triggers the load event on the img between the img.src = ... line and the img.onload = ... line. Since my handler isn't attached yet, I don't get the call, because by the time I've attached my handler, the event has already fired.

But you can see the effect of queuing if we reverse those lines:

var img = document.createElement('img');
img.onload = function() {
    // Handle the fact the image loaded
    foo();
};
img.src = /* ...the URL of the image... */;
doSomethingElse();
doYetAnotherThing();

Now I'm hooking the event before setting src. If the event fires between the img.src = ... line and the doSomethingElse line (because the browser has the image in cache), the callback to my handler gets queued. doSomethingElse and doYetAnotherThing run before my handler does. Only when control passes out of my code does the queued call to my handler finally get run. The JavaScript code is single-threaded, but the environment is not.

You can also yield to the host environment in non-obvious ways. For instance, by calling alert or its breathren confirm, prompt, etc. These functions stick out like the sore thumbs they are in modern JavaScript because they aren't event driven; instead, JavaScript execution is suspended while a modal window is shown. But as bobince points out in his in-depth discussion here, that doesn't mean none of your other code will run while that modal is showing. It's still single-threaded, but the one thread is being suspended in one place (by the modal) and used to run code elsewhere in the meantime; a very fine distinction indeed. (Bob also points to some event handling — his focus example — that seems to break this rule, but it doesn't. His example calls focus, which in turn calls the event handlers, and then returns; no different from you calling your own functions.) The key thing the items that Bob points out have in common is that your code has called into something in the host environment that does goes away and does something (shows a modal dialog, fires blur and focus handlers, etc.).

(alert and its breathren in particular cause all sorts of nastiness, particularly around focus and blur, and I recommend avoiding them in favor of more modern techniques (which can also look about 18x better).)

So those are the caveats mentioned at the outset of the answer. And in particular, if myFunction calls alert, at least on Firefox the ajax completion callback will get run during the alert (it won't on most other browsers). If you're curious to try out what does and doesn't happen during alerts and such, here's a test page testing setTimeout and ajax; you could extend the tests to go further.

How do I learn about browser host objects

23 votes

TL:DR;

I listed some host objects learning resources, but these resources don't go out of the way to teach me. Are there any proper learning resources for learning about the host objects?

Introduction:

Host objects include the DOM0-3, BOM, HTML5, WHATWG, and any other W3C standardized JavaScript based browser APIs. The collection of host objects is huge.

What are the go-to resources for actually learning about the host objects.

I have no interest in

  • "learning jQuery / <insert favourite js library>". I already know jQuery
  • "Reading W3Schools". Please don't link mediocre references.
  • "Go read the MDN". The MDN is a reference, I can't find new information without crawling it.
  • "Go read the W3C Specification". This is what I'm currently avoiding as it's dry and overly complex.
  • "Go read about these browser bugs". I'm aware learning about browser bugs and how to handle them is important but they are not relevant to this question.

I know all the trivial uses of the DOM, I understand events, I understand dispatching events, I understand querySelectors, I understand DOM tree navigation. I understand Nodes, etc.

I feel like I know a lot but I'm still only scratching the surface of how to use the host objects.

So I'm looking for a solid resource for understanding the lesser known and less common parts of the DOM including those not implemented in all browsers (or any!).

Personal Suggestions:

To learn or know the DOM I feel I would have to either

  • Sit down and read various lengthy and dry W3C specifications
  • or Read the Webkit / Gecko source.
  • Read jsdom
  • Read Base2.DOM

Are there any better, more practical, complete, modern and upto date resources?

Other Useful Resources:

Reactions to Comments:

As @Seth mentioned :

Why not open jQuery and see how they are doing what you want to do...they do it really well so it should be a good starting point.

This is a suggestion. But the thing you really learn when reading jQuery is browser compliance. You learn quite a bit about the DOM but it's hidden by walls of browser hacks.

As mentioned if you want to learn about the DOM through reading code, go read jsdom or base2.DOM

As @adatapost mentioned:

I'd like to suggest the book JavaScript: The Good Parts.

The Good Parts teaches you EcmaScript. I know EcmaScript. I want to know the host objects.

As @alexantd mentioned

I want to learn the DOM and I already know exactly what I need to do, but I don't want to do any work. Help.

Yes it may sound like this. But I'm saying I know of ways I can learn about the host objects but they are not ways tailored to teaching me the Host objects. Are there any better ways?

Since it seems no-one wants to answer the question, I'll give it a shot. I already told you in the Javascript chat channel, that the question asked is pretty vague (which you agreed). The problem is, the word DOM pretty much like the BOM (Document Object Modell & Browser Object Modell) are beasts which are a living creatures and they got extended over years (decades?).

The DOM actually is only an interface (even if it was not supposed to be one originally) to the ECMAscript world. A way to access the (X)HTML or XML markup via script.

What you are looking for, is probably a compendium of all available Host objects and all the methods those expose to you. I have to admit, I don't know about such a source but that might be for a good reason. I already mentioned that the DOM is in flux and a living creature, there are so many differences on different platforms/browsers that it probably does not make much sense to create such a compendium at all.

Of course there is MDC, but that again sounds pretty much like a 'one mans opinion'. Crockfords talk about "the DOM" is also pretty pretty basic stuff. If anybody knows a source which describes any method in any browser Host object for all browsers, I'd be pretty surprised but happy aswell.

Question about multiple ready()'s

21 votes

Suppose I have:

<script src="script1.js"></script>
<script src="script2.js"></script>

Both of these scripts have ready() inside. Will the code in script2.js's ready() always execute after the first one?

Yes.

First of all, the code in script2.js will be executed after script1.js, as it comes later in the document (and the defer attribute is not set).

Furthermore, the implementation [source] of the ready function is:

ready: function( fn ) {
    // Attach the listeners
    jQuery.bindReady();

    // Add the callback
    readyList.done( fn );

    return this;
},

where readyList seems to be [source] a deferred object [docs]. That means the callbacks are executed in the order they have been added to that object.

Reading a javascript script, why so many $ (dollar signs)?

21 votes

I am trying to decipher a .js script and I am finding it filled with $ throughout? Is there any reason to use this? I'm pretty new to JavaScript.

I think you are reading a javascript library famously known as jQuery(or possibly another library). The $ is just a short form for a namespace or use as an identifier.

You can think of it like this jQuery('p') to select all the paragraphs on a page, or for short form you can just write $('p').

Here is a link for jquery tutorials/docs jQuery

Here is a list of standards section 7.6 describes it in detail ecma standard

Can search engine spiders see content I add using jQuery?

20 votes

I currently have something like this

<p class="test"></p>

<script type="text/javascript">
    $(document).ready(function() {
          $(".test").html("hey");
    });
</script>

Will search engines be able to spider the "hey" text? and if yes, what method can I use to prevent that.

Despite what is being stated here in other answers and totally contrary to Google's own FAQ, a Google employee named JohnMu answered a question recently in Google Groups about how the GoogleBot came to follow a non-existent URL. (The actual URL was contained within the jQuery code itself and the GoogleBot DID try to follow it.)

jQuery causing 404 errors in Google Webmaster Tools

Google Employee explains how JavaScript and jQuery are indexed

Apparently, Google does attempt to index your JavaScript.

Quote Google's JohnMu:

"I would also recommend not explicitly disallowing crawling of the jQuery file. While we generally wouldn't index it on its own, we may need to access it to generate good Instant Previews for your site."

JohnMu later in the same thread...

"Additionally, we're constantly working on improving processing of JavaScript for web-search in general, so if you use jQuery to pull in content, and the jQuery script is disallowed for Googlebot, then we would not be able to look at that at all."

What exactly does $(document).ready guarantee?

17 votes

Running my (rather complex) JavaScript/jQuery application in Google's Chrome browser, it would appear that $(document).ready fires while some of the JavaScript files have not yet loaded.

The relevant code (simplified):

In my HTML file

<script>var httpRoot='../../../';var verifyLoad = {};</script>

<script src="../../../globalvars.js"></script>
<script src="../../../storagekeys.js"></script>
<script src="../../../geometry.js"></script>
<script src="../../../md5.js"></script>
<script src="../../../serialize.js"></script>
...
<script src="../../../main.js"></script>

As the last statement of each of the .js files except main.js:

verifyLoad.FOO = true; // where FOO is a property specific to the file

e.g.

verifyLoad.jquerySupplements = true; 

verifyLoad.serialize = true; 

In main.js:

$(document).ready(function() {
    function verifyLoadTest (scriptFileName, token) {
        if (!verifyLoad.hasOwnProperty(token)) {
            console.log(scriptFileName + ' not properly loaded'); 
        };
    };
    verifyLoadTest('globalvars.js', 'globalvars');
    verifyLoadTest('storagekeys.js', 'storagekeys');
    verifyLoadTest('geometry.js', 'geometry');
    verifyLoadTest('md5.js', 'geometry');
    verifyLoadTest('serialize.js', 'serialize');
    ...
}

Much to my amazement, I see some of these trigger. This does not match my understanding of $(document).ready. What am I missing?

The document's ready event is fired when the browser has parsed the HTML file from beginning to end and converted it into a DOM structure. It does not in any way guarantee that any other resources (e.g. stylesheets, images or, as in this case, scripts) will have loaded. It only refers to the DOM structure, and is fired irrespective of the loading status of the page's resources.

If you want to wait for resources to load, use the window's load event, which is fired only when every element on the page has finished loading.

See:

Why is ( Infinity | 0 ) === 0?

17 votes

I'm fiddling around with bitwise operators in JavaScript and there is one thing I find remarkable.

The bitwise or operator returns 1 as output bit if one of the two input bits are 1. So doing x | 0 always returns x, because | 0 has no effect: ( 1 | 0 ) === 1 and ( 0 | 0 ) === 0.

However, when I calculated Infinity | 0, I got 0. This is surprising in my opinion, because by the above one should get Infinity. After all, ( x | 0 ) === x.

I cannot find where in the ECMA script specification this is explicitly defined, so I was wondering what exactly implies that ( Infinity | 0 ) === 0. Is is perhaps the way Infinity is stored in memory? If so, how can it still be that doing a | 0 operation causes it to return 0 whereas | 0 should not do anything?

Bitwise operators work on integers only.
Infinity is a floating-point value, not an integer.

The spec says that all operands of bitwise operations are converted to integers (using the ToInt32 operation) before performing the operation.

The ToInt32 operation says:

If number is NaN, +0, −0, +∞ or –∞ return +0.

Self destructing Javascript function - How does it work?

17 votes

So I found this piece of code and it obviously works (as it has been in production for years):

window[someMethod] = function (tmp) {
    callback({prop:"val"}, tmp); 

    // Garbage collect
    window[someMethod] = undefined;
    try { 
        delete window[someMethod]; 
    } 
    catch (e) { }
    if (head) { 
        head.removeChild(script); 
    }   
    // head refers to DOM head elem and script refers to some script file elem
};

Curious to know, how does it work?

  1. How can it set itself to undefined within its body and try to delete itself?
  2. Does the browser know to not execute the undefined and delete until the call is finished? And how?
  3. If the browser deletes it right away, then what happens after? Does the last line run?
  4. Finally, do you guys see this leaking memory? If yes, how?

  1. It's not setting itself to undefined, it's setting a reference to itself to undefined. If you think of a function as a block of code in memory, that block of code isn't deleted in this case, just the reference to it. You never explicitly delete anything in JavaScript, you simply remove references to it and leave it to the garbage collector to clean up. Note, this might not be the case for actual code, just heap objects, as its up to the engine how to treat it (interpret it, compile it, execute it on an abacus, whatever)
  2. Based on that logic, once the function is executing, the original reference to it is no longer required as it was needed only initially to transfer execution to it.
  3. You're misunderstanding JS evaluation as requiring a reference to it for every statement. In all likelihood, this method has been Just-In-Time compiled and is now executing just like any other non-JS function would run.
  4. There are no apparent memory leaks in the code above.

Hopefully this is making sense.

How robust is nodejs as an http server?

16 votes

If I use the http module of nodejs to make a simple http server, how much validation/checking do I have to do?

Does the module take care of security issues like malformed requests and requests with malicious header values? Does the module ensure that everything follows the http spec, or do I have to do a lot of checking to make sure that my server isn't easy to crash?

Edit: Let's say nodejs doesn't do any real validation, which I'm pretty sure is the case. What do I have to do to make sure my server isn't easily crashable?

What is a malicious header value? Node is low level, so a lot of things aren't checked. But you have to look at those things. But it isn't like someone can send "execute 0xFA894224" or something. The only holes it's likely to have are things like allowing malformed request (eg, maybe you might get request.location: "\*\*\* CHINAAA \*\*\*", forgetting to launch a socket close event, or throwing a JavaScript error and gracefully terminating.

You can always check yourself for these things, or use a try catch block, process.on, etc. Of course, it's not to say there might not be a buffer overflow or something somewhere, but it is unlikely considering node is built on top of v8, and many of the libraries are pure JavaScript

Edit: How to stop random crashes:

process.on('uncaughtException',function() {
 /* ignore error */
});

What are the disadvantages of JavaScript prototype inheritance?

15 votes

I recently watched Douglas Crockford's JavaScript presentations, where he raves about JavaScript prototype inheritance as if it is the best thing since sliced white bread. Considering Crockford's reputation, it may very well be.

Can someone please tell me what is the downside of JavaScript prototype inheritance? (compared to class inheritance in C# or Java, for example)

Things I miss when sub-classing an existing object in Javascript vs. inheriting from a class in C++:

  1. No standard (built-into-the-language) way of writing it that looks the same no matter which developer wrote it.
  2. Writing your code doesn't naturally produce an interface definition the way the class header file does in C++.
  3. There's no standard way to do protected and private member variables or methods. There are some conventions for some things, but again different developers do it differently.
  4. There's no compiler step to tell you when you've made foolish typing mistakes in your definition.
  5. There's no type-safety when you want it.

Don't get me wrong, there are a zillion advantages to the way javascript prototype inheritance works vs C++, but these are some of the places where I find javascript works less smoothly.

4 and 5 are not strictly related to prototype inheritance, but they come into play when you have a significant sized project with many modules, many classes and lots of files and you wish to refactor some classes. In C++, you can change the classes, change as many callers as you can find and then let the compiler find all the remaining references for you that need fixing. If you've added parameters, changed types, changed method names, moved methods,etc... the compiler will show you were you need to fix things.

In Javascript, there is no easy way to discover all possible pieces of code that need to be changed without literally executing every possible code path to see if you've missed something or made some typo. While this is a general disadvantage of javascript, I've found it particularly comes into play when refactoring existing classes in a significant-sized project. I've come near the end of a release cycle in a significant-sized JS project and decided that I should NOT do any refactoring to fix a problem (even though that was the better solution) because the risk of not finding all possible ramifications of that change was much higher in JS than C++.

So, consequently, I find it's riskier to make some types of OO-related changes in a JS project.

Are there any drawbacks to using anonymous functions in JavaScript? E.g. memory use?

15 votes

At some point in the past, I read something that gave me the idea that anonymous functions in JavaScript can use up a surprising amount of memory (because they carry the entire current scope around with them), whereas named (static?) functions don’t have this issue.

I can’t remember where I read this, so I can’t go back and re-read it and figure this out for myself.

I’ve got two questions:

  1. Are there situations where anonymous functions can use enough memory for it to be worth caring about? (If so, do you have an example?)
  2. Are there any other drawbacks to anonymous functions (as opposed to named/static functions)?

All JavaScript functions will behave in the same manner in that they inherit the variable environments in entire scope chain leading up to, and including, themselves. This is equally true for both anonymous and named functions.

This chain of references to the outer environments stays with each function, even if the function is passed into an entirely different scope.

Traditionally, this would mean that all variables in any given chain have a reference retained to them as long as the inner closure continues to exist. Although in modern browsers that compile the code, it is likely that there will be an analysis of which variables are actually referenced, and only those will be retained, allowing others that are no longer referenced to be garbage collected.

However, there are other situations where an anonymous function is wasteful.

Here's a common bit of code:

for( var i = 0; i < 100; i++ ) {
    (function( j ) {
        setTimeout( function() { console.log( j ); }, 1000 );
    })( i );
}

This is a situation where an anonymous function is a bit more wasteful than a named function because you're recreating an identical function 100 times during the loop when you could just reuse a named one.

function setConsole( j ) {
    setTimeout( function() { console.log( j ); }, 1000 );
}

for( var i = 0; i < 100; i++ ) {
    setConsole( i );
}

This has the exact same closure overhead, but is more efficient because you've only constructed one function to create each new variable environment.

http://jsperf.com/immediate-vs-named (Thanks to @Felix Kling for the jsPerf.)

So with respect to the closure in particular, yes there's overhead as long as you maintain the closure by some permanent reference. I'd say that it is good to avoid this if possible but not to be obsessive about it. Sometimes a new variable environment added to the scope chain is simply the best solution.


EDIT: Here's an article from Google. Specifically, see Avoiding pitfalls with closures. for information on the performance impact of extending the scope chain, and for a claim that anonymous functions are “slower” than named functions.

is "<script type='text/javascript'>" incorrect?

15 votes

On aminutewithbrendan, brendan eich makes an off hand comment implying that serving scripts as

<script type='text/javascript'></script>

is not correct because "text/javascript" is not a valid MIME type and he states "application/javascript" is a valid MIME type.

I only care about serving HTML5 as the doctype.

  • Where are the MIME types for <script> defined in the html5 W3C specification ?
  • What is browser support like for "text/javascript" and "application/javascript" ?
  • Which should be used ? Alternatively should we just not set type at all?

Literal Quote from brendan: (1:48)

... or script type equals application/javascript or application/ecmascript, those are the official MIME types or either one of those made-up ones from HTML4 like text/javascript ...

Related:

The union of the related resources doesn't really answer all three questions.

Where are the MIME types for <script> defined in the html5 W3C specification ?

Nowhere, it has a list (which includes some experimental and deprecated ones) but states that you can use any MIME type you like. MIME types are defined by IANA and text/javascript is officially marked as obsolete in favour of application/javascript

What is browser support like for "text/javascript" and "application/javascript" ?

Not good enough. There are still plenty of browsers around that don't recognise the latter. (This is, however, only a problem with the type attribute, you can set the HTTP Content-Type header correctly without worrying).

Which should be used ? Alternatively should we just not set type at all?

Since you only care about HTML 5, just omit the type attribute entirely. It is optional and the default language is JavaScript.

Does the asset pipeline rails 3.1 waste cycles?

13 votes

In rails 3.1, does .coffee and //= require files get processed only once or with each asset request?

For example,I have a file


//= require source/main.js.coffee
//= require source/second.js.coffee
//= require source/third.js.coffee

Ideally, the server would compile these to js ONCE, then bundle them, then create a static file. But if it happens on each asset requests,it's going to be wasting cycles repeating it??

Thanks for any guidance on this.

Yes, the assets will be compiled AND cached. So they won't generate additional cycles. You can also pre-compile them before you push them to production.

Here is a good writeup: http://blog.nodeta.com/2011/06/14/rails-3-1-asset-pipeline-in-the-real-world/

Why serve 1x1 pixel GIF (web bugs) data at all?

13 votes

Many analytic and tracking tools are requesting 1x1 GIF image (web bug, invisible for the user) for cross-domain event storing/processing.

Why to serve this GIF image at all? Wouldn't it be more efficient to simply return some error code such as 503 Service Temporary Unavailable or empty file?

Update: To be more clear, I'm asking why to serve GIF image data when all information required has been already sent in request headers. The GIF image itself does not return any useful information.

Doug's answer is pretty comprehensive; I thought I'd add in an additional note (at the OP's request, off of my comment)

Doug's answer explains, in a comprehensive way, why 1x1 pixel beacons are used for the purpose they are used for; I thought I'd outline a potential alternative approach, which is to use HTTP Status Code 204, No Content, for a response, and not send an image body.

204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Basically, the server receives the request, and decides to not send a body (in this case, to not send an image). But it replies with a code to inform the agent that this was a conscious decision; basically, its just a shorter way to respond affirmatively.

From Google's Page Speed documentation:

One popular way of recording page views in an asynchronous fashion is to include a JavaScript snippet at the bottom of the target page (or as an onload event handler), that notifies a logging server when a user loads the page. The most common way of doing this is to construct a request to the server for a "beacon", and encode all the data of interest as parameters in the URL for the beacon resource. To keep the HTTP response very small, a transparent 1x1-pixel image is a good candidate for a beacon request. A slightly more optimal beacon would use an HTTP 204 response ("no content") which is marginally smaller than a 1x1 GIF.

I've never tried it, but in theory it should serve the same purpose without requiring the gif itself to be transmitted, saving you 35 bytes, in the case of Google Analytics. (In the scheme of things, unless you're Google Analytics serving many trillions of hits per day, 35 bytes is really nothing.)

You can test it with this code:

var i = new Image(); 
i.src = "http://sharedcount.com/test/beacon.gif";

What I'm not sure about, since I haven't tested it, is if this results in any browser quirks, but it will definitely serve the same purposes as the 1x1 beacon. (For example, Chrome sends the request, but deems the request "Cancelled" in the Dev Tools, since no body was transferred back. But, the request definitely makes it to the server, since there are response headers.)

CSS rules with multiple possible values (jQuery)

13 votes

The question is simple; using jQuery's css function, the computed style of a CSS attribute may be returned, but what if there are more than one style for that attribute being rendered? For example :

<div id="foo" style="text-decoration:underline;">Some underline text</div>

The instruction $('#foo').css('text-decoration'); will return underline. Now if I change it to

<div id="foo" style="text-decoration:underline;">Some underline <span id="bar" style="text-decoration:line-through;">text</span></div>

The instruction $('#bar').css('text-decoration'); will return line-through, alright.

But the actual text is also underline! How can I return both? Do I need to search all ancestors if I want to know if some text is both underline and line-through? Sounds a bit painful, no?

** Edit **

Another problem arises whith this HTML

<span style="text-decoration:underline;">some <span id="e1" style="font-weight:bold;">text</span></span>

where $('#e1').css('text-decoration'); returns none for some reason, while the text is clearly rendered with an underline.

** Disclaimer **

This question is not to debate how the UA renders an element, but if an element hierarchy applies a CSS or not. If one wants to understand text-decoration better, I suggest one would read about it. The question tries to focus on a more generalize matter. For example, it can also apply to this HTML

<div style="display:none;">Some <span id="keyword" style="text-decoration:underline;">hidden</span> text</div>

where one could want to know if the element keyword is visible or not. With the code below, this is simply done with

cssLookup($('#keyword'), 'display', 'none');   // -> true

** UPDATE **

After all the answers and comments, here is, based on Brock Adams solution :

/**
 * Lookup the given node and node's parents for the given style value. Returns boolean
 *
 * @param e     element (jQuery object)
 * @param style the style name
 * @param value the value to look for
 * @return boolean
 */  
function cssLookup(e, style, value) {
    var result = (e.css(style) == value);
    if (!result) {
        e.parents().each(function() {
            if ($(this).css(style) == value) {
                result = true;
                return false;
            }
        });
    }

    return result;
}

Thank you, everyone, for your inputs.

I don't think any browser, or the W3C, provides a good way to do this.

A complicating factor is knowing which styles cancel preceding styles (underline versus no-underline, for example).

So, we would need multiple look-up tables or human judgement to know which style actually applied.

Finally, all these methods (3 answers so far) cannot distinguish between a blank, or missing, style setting and an explicitly set none. Obviously the browser can render an explicitly set none differently than a blank or missing setting.

For human use, this code should do the trick:

function cssTree (jNode, styleName, bShowBlanks) {
    var styleArray  = [jNode.css (styleName)];

    jNode.parents ().map ( function () {
        var style   = $(this).css (styleName);

        if (bShowBlanks  ||  ! /^(none|\s*)$/i.test (style) )
            styleArray.push (style);
    } );
    return styleArray;
}

alert ( cssTree ( $("#bar"), 'text-decoration') );


See it in action at jsFiddle.

Results:

bar: line-through,underline
el: none,underline

//-- With bShowBlanks = true.
bar: line-through,underline,none,none
el: none,underline,none,none

What function acts as .SelectMany() in jQuery?

13 votes

Let me explain more:

we know that map function in jQuery acts as .Select() (as in LINQ).

$("tr").map(function() { return $(this).children().first(); }); // returns 20 tds

now the question is how can we have .SelectMany() in jQuery?

$("tr").map(function() { return $(this).children(); }); // returns 10 arrays not 20 tds!

here is my example in action: http://jsfiddle.net/8aLFQ/4/
"l2" should be 8 if we have selectMany.

[NOTE] please don't stick to this example, above code is to just show what I mean by SelectMany() otherwise it's very easy to say $("tr").children();

Hope it's clear enough.

map will flatten native arrays. Therefore, you can write:

$("tr").map(function() { return $(this).children().get(); })

You need to call .get() to return a native array rather than a jQuery object.

Why does this document.write iframe ads code completely break Internet Explorer?

12 votes

So, I'm trying to find an answer to why this problem is happening; I've fixed the problem, but I want to know why it happened.

TL;DR

Google-provided conversion tracking code that injected an iframe using document.write suddenly caused the page to cease to execute in all versions of Internet Explorer, but was remedied by injecting the same iframe using a non-document.write method.

The Story:

Doubleclick is an advertising network that provides a JavaScript snippet to track conversions from ads.

The snippet they give looks like this:

<SCRIPT language="JavaScript">
var axel = Math.random()+"";
var a = axel * 10000000000000;
document.write('<IFRAME SRC="https://fls.doubleclick.net/activityi;src=143;type=donat01;cat=indir4;ord=1;num='+ a + '?" WIDTH=10 HEIGHT=10 FRAMEBORDER=0></IFRAME>');
</SCRIPT>
<NOSCRIPT>
<IFRAME SRC="https://fls.doubleclick.net/activityi;src=143;type=donat01;cat=indir4;ord=1;num=1?"
WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>
</NOSCRIPT>

Now, I know that, for all sorts of reasons, document.write is hazardous and should be avoided. But, Google is giving me this code, so, I figured I could trust it.

It suddenly started breaking all of our pages for all users using Internet Explorer. As in, the page would stop rendering entirely once it hit the document.write. This was crazy: One of the largest third party advertisers on the internet had given me JavaScript that had LITERALLY broken my purchase pages for 25% of my traffic!

As triage, I quickly substituted in the same code using the injection technique found in Google Analytics:

var iframe = document.createElement('iframe');
iframe.src = //the URL;
iframe.width = 0;
iframe.height = 0;
iframe.frameborder = 0;
var ref = document.getElementsByTagName('script')[0];
ref.parentNode.insertBefore(iframe, ref);

This resolved the problem, without actually explaining:

Why does a nearly empty iframe, injected using document.write, break Internet Explorer, but this method above doesn't?

I've solved the problem; it turns out that it had nothing to do with the contents of the <iframe>.

It turns out the page is served by a framework that began using a backend DOM parser that, for reasons likely related to the presence of </ within a <script> tag within the document.write, completely removes the </iframe> tag from the generated page, even though it preserves it in the backend. (It's probably trying to enforce ETAGO rules).

The reason I was able to reproduce it was because I was copying the generated document.write code, not the original code, and never noticed the missing </iframe>. (And my "functioning" document.write code didn't have the stripped out </iframe> tag, leading me to believe that the problem was the contents of the iframe.)

As a result, browsers parsed an unclosed <iframe> tag on the page, which Internet Explorer didn't know how to handle, and died part way through the parsing of the iframe (I'm still not totally sure why).