• Home
  • New Entries
  • Popular Entries
  • Submit a Story
  • About

A better JavaScript code evaluation ...

It seems to be a simple and basic question but He was right because the answer is: yes, a script tag is generally interpreted faster than code evaluation using eval, execScript or Function constructor.

I suppose the reason is quite obvious: eval, as execScript or Function, brings temporary local scope inside evaluated code and this cause a little overhead while a script tag is always interpreted only inside global scope (window or super object).

This should be a limit for evaluation common usage (often wrong) but this was the primitive Ajax implementation to interact with server.

Example:

// specific callback to show product informations
function productInfoCallback(product){
 alert(product);
}

// function to send something using GET way (query string)
function sendRequest(queryString, callback){
 var s = document.createElement("script");
 s.type = "text/javascript";
 s.src = "interactor.php?".concat(queryString, "&callback=", callback);
 (document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0])
  .appendChild(s).parentNode.removeChild(s);
};

// generic product id
var productId = 123;

// interaction
sendRequest("productId=".concat(productId), "productInfoCallback");



Now try to image server side code, in this case a really simple PHP script:

if(isset($_GET[productId], $_GET[callback])){
 $productInfo = Web Reflection Blog;
 //$productInfo = mysql_query ...
 header(Content-Type:text/javascript);
 exit($_GET[callback].(".addslashes($productInfo)."));
}
?>



Well done, this is Ajax without Ajax ... a sort of Asyncronous JavaScript and JavaScript (could we call them Ajaj ? :D )


At this point You should agree that there is no way to inject temporary scope inside response and when You load manually or dynamically a script tag the behaviour is the same.

Is it ok? Is it clear?

Well, next step is to use script tag instead of code evaluation to perform quickly (I am talking about milliseconds) expecially when We use Ajax to recieve a JSON string.

With JSON We usually don need temporary scope so why We should "wait" more time to evaluate that string?

This is an elementary proposal, the function evalScript:

(evalScript = function(e){
 var h = evalScript.node,
  s = document.createElement("script");
 s.type = "text/javascript";
 s.text = e;
 h.appendChild(s);
 h.removeChild(s);
}).node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];



How to use them? It is really simple:


// basic example
evalScript(alert("Hello World"));



The only thing You need to remember is that scope is not injected inside evaluation:

function badEvalScript(){
 var string = "something";
 evalScript(var string2 = string + " else");
};

badEvalScript();
// string is not defined
// ... and string2 will be global (window.string) if string is defined




So how to use evalScript ?
You can use them after one or more Ajax interaction if You are loading a script, instead of XML or (x)HTML or text, to run for example dinamically external resources.

You can use evalScript with JSON interactions too, but You should use a little trick if You don want to be obtrusive.

The simplest solution is, in fact, this one:

evalScript(JSONResponse = .concat(xhr.responseText));


... but in this web world full of different libraries this is not a good idea, so why don use evalScript itself to store temporary results?

// generic Ajax interaction ...
evalScript(evalScript.result = .concat(xhr.responseText));
var response = evalScript.result;



Since JavaScript is, at least inside browsers, single thread, there is no risk about concurrency and in this way You will not overwrite anything different from single evalScript function.

If You don believe this function is usually faster than eval, just try to generate a big and complex JSON notation, using every compatible kind of compatible value, so try 10 or more times to eval them or to use my evalScript proposal.

Update
You can use evalScript to solve correctly global scope code evaluation too, sorry John (and jQuery team) but I suppose that eval.call(window) and setTimeout(f,0) aren a "realistic" solution (first one requires this inside evaluation while second one, I suppose, is not syncronous).

function globalScopeEvaluation(){

 var testMe = "private scope";
 evalScript(alert(testMe));

};

var testMe = "global scope";

globalScopeEvaluation(); // global scope



Finally, if You call another function to evaluate something, its scope is just global, You don need to use eval.call or other strategies, am I wrong?

function eval2(data){eval(data)};
var a = 1;
(function(a){eval2(alert(a))})(2);
// alert 1 ...
source:

 View Full Story.

AddThis Social Bookmark Button

Posted at 08:54:06 am | Permalink | Posted in Javascript  

Related Stuff

  • MooV: Using cutting edge Video phones and Software Video Phones - coupling all that with VoIP and empowering the disabled.

  • Moo Telecom: VoIP communications made easy - Ring anyway with the fun and ease of using a normal phone

  • TagR:Mobile Social Network with Real Time Locations Based services, and Ambience Intelligence, VoiP, IM, Skype, Googletalk, Mapping, Flickr, Events, Calendaring, Scheduling, SecondLife Support

  • ClearSMS : ClearSMS is a Web-based application that lets you send bulk SMS messages to your customers, contacts, or just about anyone.

  • Jajah:jah is a VoIP (Voice over IP) provider, founded by Austrians Roman Scharf and Daniel Mattes in 2005[1]. The Jajah headquarters are located in Mountain View, CA, USA, and Luxembourg. Jajah maintains a development centre in Israel.

  • Skype: It’s free to download and free to call other people on Skype. Skype the number one voice over ip software

  • PrivatePhone: a free local phone number with voicemail and messages you can check online or from any phone.

Top Stuff

e-messenger

MessengerFX

eBuddy

ILoveIM

AIM Express

Top 20 Ruby CMS


Love Poems

best love poems

Custom Software Development

High quality software development at low prices. PHP, ASP.NET, AJAX

Wordpress Themes

Unique Themes & Templates for wordpress, download and create your own.

Stock Exchange Chat

Stock exchange community, chat room for each quote

eBuddy

web based messaging for everyone, everywhere.

Self Imrovement

Videos for self improvement, self help, communication skills

MSN Web Messenger

MSN Web Messenger full review, tips and screen shots.

qualities of a good supervisor

What makes a good supervisor? There are a number of qualities and characteristics which indicate a good supervisor.

Facebook Applications

Do you want to know the latest facebook applications?

Egyptian cotton bed

Visit Aqttan online store for famous egyptian cotton home textile products.


About Ajaxlines

Ajaxlines is a project focused on providing its audience with a database of most of Ajax related articles, resources, tutorials and services from around the world.

Its purpose is to showcase the power of Ajax and to act as a portal to the Ajax development community.


Search


Topics

  • .Net (118)
  • Ajax (24)
  • Ajax Games (10)
  • Articles (95)
  • Bookmarking (35)
  • Calendar (19)
  • Chat (41)
  • ColdFusion (3)
  • CSS (52)
  • Email (23)
  • Facebook (47)
  • Flash (17)
  • Google (36)
  • Html (17)
  • Image (11)
  • International Calls & VOIP (7)
  • Java (41)
  • Javascript (196)
  • jQuery (11)
  • JSON (26)
  • Perl (2)
  • PHP (101)
  • Presentation (19)
  • Python (3)
  • Resources (2)
  • RSS (2)
  • Ruby (16)
  • Storage (4)
  • Toolkits (96)
  • Tutorials (203)
  • UI (12)
  • Utilities (173)
  • Web2.0 (18)
  • XmlHttpRequest (22)
  • YUI (4)

© 2006 www.ajaxlines.com. All Rights Reserved. Powered by IRange