views:

40

answers:

2

I write a lot of bookmarklets and I put them inside a meta-bookmarklet (>20kb so far) thus:

var uGlY_vArIaBlE=(function(){
  var d=document;
  var f1=function(){};
  var f2=function(){};
  …
  … /* lot of code here */
  …
  var f50=function(){};
});
uGlY_vArIaBlE();

Is it okay for me to assume that f50 will 'know' that d=document as fast as f1 would? Also how does a browser actually read/interpret a script (injected or loaded from the cache)? I don't seem to be experiencing any significant delays. Any tips you could share please.

A: 

The only delay a long script should cause is in loading and parsing. It will take longer to load the script from disk (because the file size is bigger), and it will take longer to parse the script so it can be executed (because there is more code to parse).

Other than that, you should not get any slowness (unless your algorithms require optimization, but that's a whole other topic)

Jani Hartikainen
+2  A: 

Your variable will be equally fast in all functions of the same level. Only inner functions lose some speed, e.g:

function f32(){
  function f33(){
    // to get d, we have to walk up 2 levels
    // so it is a bit slower to get it then
    // it is for f32
  };
};

A bit better concept would be:

(function( window, undefined ){ // <- no need to name it (can be anonymus)

var d = window.document;

function f1(){};
function f2(){};

// .............

function f50(){};

})( window ); // <- it will be executed immediately

And both document and window will be faster, since they are local variables.

galambalazs
galambalazs Why the param 'undefined'?
Iamthealphaandtheamigo
because minifiers will be able to shrink it, and defining your own undef prevents 3rd party code from breaking yours.
galambalazs