March 22, 2010

jquery replacement

as i begin to make mobile apps, it’s become painfully clear that i simply don’t have the performance i’m used to in a browser. while i write fast javascript, i am stuck using jquery for the time being. I’m not a jQuery fan, but i’m not out to get it either. it is what it is, and it works.

The problem is that it works slowly. I re-wrote the fade routine a few months back. mine uses 1/3 the cpu of jQuery’s native routine. I wanted more than just faster fades, i want fast everything, so i began another library.

I don’t think it will replace jQuery, which at this point has a million nooks and crannies to replaicate. After reviewing what i use jQuery for, and what takes a long time to run, i’ve settled a a subset of functionality. The syntax is similar, but not compatible with jQuery.

On the technical end, it’s based around Arrays of elements instead of jQuery’s custom objects. This lets me use [].map(), [].filter(), etc on the result set. The css selector is next gen: querySelectorAll() only, no backwards css path decoding codebase. I have the usual methods like show, attr, html, hide, each, toggle, css, events, etc at least partially working.

the whole thing is currently ~2kb compressed, and performs about 8-12X faster than jQuery.
It’s complimenting to jQuery and does the same basic things, but fast.
if anything becomes of it, i’ll let you know.

December 28, 2009

libraries

i had sworn off creating libraries, but i can’t stop myself. I will be releasing three new libraries in the next few weeks.

1. a sequal to my F functional programming library, this time with several Function prototypes.
2. a Haskell data.list array method [].prototype package. almost all the Haskell functions are done.
3. a 10kb version of Prototype, all the same String and Array methods with some other bonuses.

stay tuned for updates.

October 8, 2009

on accessibility

use consistent html from page to page.
even if your page is hard to use, a user knowing they have to jump ahead 20 links each page visit saves them a ton of time. if each page is different, that predictability is lost. It’s like the difference between cooking in your own kitchen versus a strangers. don’t make them constantly “look” around.

sectionize everything.
the idea is to group related info and features together so that a user can jump to a section, and then find the part they needed. imagine a grocery store without aisles or signs, how would anyone find anything?

like a store, use big signs to point to your most important sections.
h1s for nav, content and footer.
h2 for content sections
h3 for each paragraph (or two or three) of page content.


standard sections include headers, navigation, content, contact info, table of contents, and footers.


add a “skip to” menu, or use ARIA landmark roles.

don’t use <br>, use <p> or <ul> tags.

don’t put meaning less text (“click here”, “more…”) inside of links, use the text as a label for the content. (“download page”, “NYT article about polar bears”).

don’t repeat yourself in link text, each should be unique.
if not possible, use the title attrib to add more info.

make the text of the navigation menu as short and direct as possible.

Place the most important word first, or asap, in all H1-5, labels, legends, and A tags.
to wit: never label like:
Enter your name, Enter your address, Enter your zip…

realize that there is no skimming, or glancing: they have to wait for steven hawking to read the label to them before they decide if that’s what they want.
the less they have to listen to, the faster and easier your site will be to use, which reflects well on you.

if you make a flowchart of how a screen reader user would navigate your site, keep in mind that H tags, legends, and links are the decision points.


people who read screens will benefit from these changes as well.

October 4, 2009

35char jsonp fetcher for jQuery

//so you can paste into firebug
    $=jQuery;

// verify script load (just for this demonstration)
    window.mini=function(){alert('hello');}

//here's how to add a script:
    $("head").append("<script src='http://danml.com/mini'>"); 

July 3, 2009

Temporary CSS

Given the text of a styleSheet (strCSS), it will apply the styles to the current document.
The next time it’s called, the old styleSheet is replaced by the new text.
In this fashion, you can quickly create conditional styles document-wide.


The function returns the text it was fed, so you can use it in a chain.

function useCSS(strCSS) {
	var D = document, ns, nsx, h = D.getElementsByTagName("head");
	if (!h[0]) {
	  return;
	} else {
	  h = h[0];
	}
	if (!useCSS._css) {
	  ns = D.createElement("style");
	  ns.type = "text/css";
	  h.appendChild(ns);
 	  useCSS._css=ns;
	} else {
	  ns = useCSS._css;
	}
	if (nsx = ns.styleSheet) {
	  return nsx.cssText = strCSS;
	} else {
	  ns.innerHTML = ""; 
	  ns.appendChild(D.createTextNode(strCSS));
	}
	return strCSS;
}

June 15, 2009

Sprint for JavaScript

usage: “Inside a string id\n or \n “ (where id is (optional) token from table below, and n is the argument position to substitute.

	"":	String (default)
"$": String
"#": Number
"%": Integer
"!": Boolean
"_": Char from charCode
"@": Locale version

javascript code:

function sprint(str){var S=String,A=arguments,c=S.fromCharCode,T={ "": S, "$": S, "#": Number, "%": parseInt, "!": Boolean, "_": function(n){return c(parseInt(n,10));}, "@": function(V){return V.toLocaleString ? V.toLocaleString() : S(V); } }; return S(str).replace(/([@#%$!_]?)([\x00-\x08])/g, function(a,t,p){return T[t||""](A[p.charCodeAt(0)],10); }); }//end sprint()

examples:

sprint(  "Hello $\1. You are %\2 years old \1."  , "dan", 123 );
//==”Hello dan. You are 123 years old dan.”
sprint("Number(#):#\1, Integer(%):%\1, Char(_):_\1, \
String($):$\1, Boolean(!):!\1,  Local(@):@\1,  default:\1 "  , 1234.5678 );
//==
Number(#):1234.5678, 
Integer(%):1234, 
Char(_):Ӓ, 
String($):1234.5678, 
Boolean(!):true,  
Local(@):1,234.5678,  
default:1234.5678 

May 28, 2009

what’s that function?

JavaScript lack the ability to reflect a method’s bound property name to the method’s function itself. I figured out a simple way around this:

function whoAmI(fn, that){
  for(var i in that){ 
   if(that[i]===fn){ 
      return i; 
   }
  }
} // end whoAmI()

this.fred = function john(){
  var myName = whoAmI(arguments.callee, this);
return myName;
}

fred()//==="fred"
this could be helpful to create re-usable or overloading functions that use the function’s calling context as an input in their decision structure. it can also snoop for a functions existance as a method on any object, by passing that object as the second argument. if found, you get the property name of the methods, otherwise it returns undefined.

March 24, 2009

on open source and js

I came across this register article “warning” that not all javascript is open source. I guess he doesn’t understand that all javascript run as source, so it’s all open, technically if not legally. Javascript can run, but it can’t hide.

Stallman also says that browsers should let you change the code they run, and that you should be able “to let users detect such code and specify which Javascript code they’d like to run - the original or a modified form” (register). I thought that’s what greasemonkey already was…

Perhaps he wants the entire scripting to write code he can keep up with. if wonder because ‘Stallman called Flash an “extended variant” of Javascript’. Not really, flash is closed, javascript is open. Don’t fence real webdevs in with flashers!

I mean really, all the things he complains about are non-issues for anyone with firefox and webdev skills, due to the inherent nature of javascript. The javascript global environment is a big pool, and anyone can stick their finger in…

Relax Stallman, this is your dream come true; you can read the source to google docs. try that with microsoft word!

March 4, 2009

php vs js

I find php interesting. It’s more terse and expansive than my favorite language; javascript. It reminds me of VB6 a lot; tons of built ins and keywords.

subtle syntax differences continue to frustrate me.

I am torn as to which one is a “better” language. While PHP gives you a lot of
functions to use, javascript aims for minimalism.


PHP seems to require more code to do the same thing as javascript.
this is a result of valuing functions over methods.

i am glad i learned javascript in detail first, because i know what i am missing.

consider an example function, the string reverse procedure.

function reverse($string) {
    $newstring = "";
    for($i = strlen($string); $i > 0; $i--) {
        $newstring .= $string[$i-1];
    }
    return $newstring;
}

This is very close to the same procedure in VBA, which a computer science professor demonstrated to me.

So, it seems that this is “the way” to do this. Indeed, with two minor adjustments, the function runs in javascript, giving the output expected:

function reverse($string) {
    $newstring = "";
    for($i = $string.length; $i > 0; $i--) {
        $newstring += $string[$i-1];
    }
    return $newstring;
}

so, i would not blame anyone for thinking this is a good way to do it in javascript. but it’s not. String concatenation is slow, requiring the string be rebuilt each append. Omitting a var statement creates globals that leak out of the function. Finally, and perhaps this is status quo, but the code is lengthy for what i am used to.

prototypes reduce code length. a lot.
compare a JS-only version of the same function:
function reverse(s) {
    return s.split("").reverse().join("");
}
faster to write, faster to execute, less overhead and ram also…

prototypes not only reduce code length, they are easier to program as well.
the code to the right of each dot describes a transformation to be applied to the value left of the dot. The same variable is reused throughout.
this also make it easier to modify.

if i want to also convert the output to UPPERCASE, in php i would need to wrap a function around the output. This forces me to use the mouse or several arrow key presses, balance params, and make changes to two locations.

in js, i can simply add another dot in the middle of the prototype chain, in one location, without balancing or extra keystrokes:
s.toUpperCase().split("").reverse().join("");

i don’t consider this simplistic (though it might be), i consider this concise.

February 6, 2009

site update

added an index to the site.
i figure why not let people see more than a single page.

i will be working on more creative displays, but the info is helpful, so here it is:

danml - index

January 27, 2009

president obama let us use your webpages

The US government creates and maintains vast storehouses of information. Most of these are publicly available online. Among the more useful:



  Images can come from anywhere, but text cannot. Thus the tiger mapping service has a REST API that can be used by/from any webpage. Any webpage can use image data from anywhere, like this pic:
current moon view
from the US navy


While an API for every bit of government data would be nice, i live in the real world. There is an ongoing economic crises, war, etc.

  Almost as good as an API would be simple allowable access from other pages. The information is supposed to be free. Without spending a dime, a server can be configuered to allow other webpages to fetch data from it, without a thrid party server. This allows more flexible use, greater creativivty, and removes cost barriers to upcoming programmers.

  A web page can be saved onto the desktop, thus not needing a server to view the webpage. Once viewed, that saved page can fetch data directly from government webpages that have made a configuration change or two. It’s not a security problem; this information is already accessible to any browser, server, or regular desktop application.

  The simple change would mean that all this useful data would be available to mere web pages. A 14 year old can write an application that 100 million people could use tomorrow; without cost to the programmer. Think of it as a small business incentive to individuals who are willing to work for the common good.

There are a couple way to open the tap:

If the government were to pick one, it would be the standard overnight. The Obama administration revamped the white house’s robots.txt file on day one. Perhaps they will be open to allowing small fries access to the data to create new combinations, visualizations, and services we cannot yet imagine. let’s not have any barriers that a 1kb text file cannot overcome!
January 14, 2009

green code

Netbooks, cell phones and other battery-powered devices are quickly becoming a popular way to access the web. I wonder how different kinds code impact the battery usage of these gadgets. A recent experiment showed that web pages using Flash sucked more power than pages with html and javascript alone. It says that “ajax” uses almost as much as Flash. I would presume he is talking about making additional URL request after the page loads. I can see where using the network would be a power drain.

JavaScript can be used to reduce power consumption for mundane tasks like rotating banner ads, running a “what’s new” section, or offering a photo slide show. Browsers are also getting much better at running JavaScript. Recent advances have lead to several times-fold increases in performance. This is good new for the battery life as well. If the JavaScript engine can run more efficiently, it has to draw less CPU power.


This got me thinking about performance tuning;
If you can make code that runs faster, it more likely than not uses fewer CPU executions.

takeaway:
Performance testing and optimization will not only speed up your app/page, it reduces greenhouse gasses and increases battery life.

December 4, 2008

Random thoughts

Scenario: You have 5000 people using your web site every day.

Question: whats cheaper for you: smart servers and dummy terminals, or a dumb server and smart clients?

Which one uses javascript more?

Put those 3.8Ghz web browsers to work for you, code javascript.

snippit library

now available here.


go ahead and bookmark, updates will be auto-applied in the future as they roll out.

finding square roots

here is an interesting example function for javascript. while not needed, it serves to demonstrate the procedure using javascript.

function sqrt(number){
  var guess = 2, old=0;
  for(var step=0;step<128;step++){
    old = guess;
       guess = (guess + (number/guess)) / 2;
    if(old===guess){break;}
   }
  return guess;
}