Developer of location based application, a frontend specialist for Google Maps API and page optimization.

psykmedia

timestamp: 1280490552

// Articles I have just read

// Building a custom HTML5 video player with CSS3 and jQuery - Opera Developer Community

Introduction

The HTML5 <video> element is already supported by most modern browsers, and even IE has support announced for version 9. There are many advantages of having video embedded natively in the browser (covered in the article Introduction to HTML5 video by Bruce Lawson), so many developers are trying to use it as soon as possible. There are a couple of barriers to this that remain, most notably the problem of which codecs are supported in each browser, with a disagreement between Opera/Firefox and IE/Safari. That might not be a problem for much longer though, with Google recently releasing the VP8 codec, and the WebM project coming into existence. Opera, Firefox, Chrome and IE9 all have support in final builds, developer builds, or at least support announced for this format, and Flash will be able to play VP8. This means that we will soon be able to create a single version of the video that will play in the <video> element in most browsers, and the Flash Player in those that don't support WebM natively.

The other major barrier to consider is building up a custom HTML5 <video> player — this is where a Flash-only solution currently has an advantage, with the powerful Flash IDE providing an easy interface with which to create a customized video player component. IF we want to write a customised player for the HTML5 <video> element we need to handcode all the HTML5, CSS3, JavaScript, and any other open standards we want to use to build a player!

And this is where this article comes in. This is the first of a series in which we will look at building up an easily customizable HTML5 <video> player, including packaging it as a simple jQuery plugin, choosing control types and outputting custom CSS for your own situation. In this article we will look at:

  1. Video controls
  2. Basic markup for controls
  3. Packaging the player as a jQuery plugin
  4. Look and Feel
  5. Themeing the player

We'll use jQuery for easier DOM manipulation, and jQuery UI for the slider controls used for seeking and changing the volume level. To build a scalable solution, we'll wrap everything up in a jQuery plugin.

Video controls

As professional web designers, we want to create a video player that looks consistent across browsers. Each browser however provides its own different look and feel for the player, from the minimal approach of Firefox and Chrome, to the more shiny controls of Opera and Safari (see Figure 1 for the controls in each browser). If we want our controls to look the same across all browsers, and integrate with our own design, we'll have to create our own controls from scratch. This is not as hard as it seems.

Native browser video controls

Figure 1: Native browser video controls across different browsers

All media elements in HTML5 support the media elements API, which we can access using JavaScript and use to easily wire up functions such as play, pause, etc. to any buttons we create. Because the native video player plays nicely with other open web technologies, we can create our controls using HTML, CSS, SVG or whatever else we like.

Basic markup for controls

First, we'll need to create the actual markup for the video controls. We'll need a Play/Pause button, a seek bar, a timer and a volume button and slider. We'll insert the markup for the controls after the <video> element, and wrap them up in another element.

<div class="ghinda-video-controls"> <a class="ghinda-video-play" title="Play/Pause"></a> <div class="ghinda-video-seek"></div> <div class="ghinda-video-timer">00:00</div> <div class="ghinda-volume-box"> <div class="ghinda-volume-slider"></div> <a class="ghinda-volume-button" title="Mute/Unmute"></a> </div> </div>

We've used classes instead of IDs for all elements, to be able to use the same code for multiple video players on the same page.

Packaging the player as a jQuery plugin

After creating the markup we'll have to tie our elements to the media elements API, in order to control the video's behavior. As noted before, we'll package the player as a jQuery plugin, which will also aid reuse on multiple elements.

AUTHOR'S NOTE: I'm going to assume you are familiar with the basic anatomy of a jQuery plugin, and JavaScript, so I'm only briefly going to explain the script. If you need more information on these subjects, consult Craig Buckler's How to develop a jQuery plugin tutorial, and the JavaScript section of the Opera web standards curriculum.

$.fn.gVideo = function(options) { // build main options before element iteration var defaults = { theme: 'simpledark', childtheme: '' }; var options = $.extend(defaults, options); // iterate and reformat each matched element return this.each(function() { var $gVideo = $(this); //create html structure //main wrapper var $video_wrap = $('<div></div>').addClass('ghinda-video-player').addClass(options.theme).addClass(options.childtheme); //controls wraper var $video_controls = $('<div class="ghinda-video-controls"><a class="ghinda-video-play" title="Play/Pause"></a><div class="ghinda-video-seek"></div><div class="ghinda-video-timer">00:00</div><div class="ghinda-volume-box"><div class="ghinda-volume-slider"></div><a class="ghinda-volume-button" title="Mute/Unmute"></a></div></div>'); $gVideo.wrap($video_wrap); $gVideo.after($video_controls);

Here we are using jQuery to create the video player markup dynamically (but not the video player itself), and removing the controls attribute once the script loads. That's because in cases where the user has JavaScript disabled, these controls will be useless, and he/she won't even get the native browser controls to the video element. It makes a lot more sense to start with the controls attribute present in case the script fails to load, and then removing it so the player will use our custom controls only after the script successfully loads.

Next, we'll have to target each of the elements in the controls, in order to be able to add listeners.

//get newly created elements var $video_container = $gVideo.parent('.ghinda-video-player'); var $video_controls = $('.ghinda-video-controls', $video_container); var $ghinda_play_btn = $('.ghinda-video-play', $video_container); var $ghinda_video_seek = $('.ghinda-video-seek', $video_container); var $ghinda_video_timer = $('.ghinda-video-timer', $video_container); var $ghinda_volume = $('.ghinda-volume-slider', $video_container); var $ghinda_volume_btn = $('.ghinda-volume-button', $video_container); $video_controls.hide(); // keep the controls hidden

We're targeting each control by its class; we'll keep the controls hidden until everything is ready.

Now for the Play/Pause controls:

var gPlay = function() { if($gVideo.attr('paused') == false) { $gVideo[0].pause(); } else { $gVideo[0].play(); } }; $ghinda_play_btn.click(gPlay); $gVideo.click(gPlay); $gVideo.bind('play', function() { $ghinda_play_btn.addClass('ghinda-paused-button'); }); $gVideo.bind('pause', function() { $ghinda_play_btn.removeClass('ghinda-paused-button'); }); $gVideo.bind('ended', function() { $ghinda_play_btn.removeClass('ghinda-paused-button'); });

Most browsers provide a secondary set of controls for the video in the right-click (ctrl-click on a Mac) context menu. Because of the way we are putting this together, if a user activated these alternative controls it would break our custom controls. In order to avoid this we're attaching events to the Play/Pause button itself, and the "Play", "Pause" and "Ended" listeners of the video player.

We're also adding and removing classes from our button to change the look of it, depending on the state of the video (Playing or Paused).

For creating the seek slider we'll use the jQuery UI Slider component.

var createSeek = function() { if($gVideo.attr('readyState')) { var video_duration = $gVideo.attr('duration'); $ghinda_video_seek.slider({ value: 0, step: 0.01, orientation: "horizontal", range: "min", max: video_duration, animate: true, slide: function(){ seeksliding = true; }, stop:function(e,ui){ seeksliding = false; $gVideo.attr("currentTime",ui.value); } }); $video_controls.show(); } else { setTimeout(createSeek, 150); } }; createSeek();

As you can see, we're using a recursive function, while reading the readyState of the video. We have to keep polling the video until it is ready, otherwise we can't determine the duration, and can't create the slider. Once the video is ready, we initialize the slider, and also show the controls.

Next we'll create the timer, and attach it to the timeupdate listener of the video element.

var gTimeFormat=function(seconds){ var m=Math.floor(seconds/60)<10?"0"+Math.floor(seconds/60):Math.floor(seconds/60); var s=Math.floor(seconds-(m*60))<10?"0"+Math.floor(seconds-(m*60)):Math.floor(seconds-(m*60)); return m+":"+s; }; var seekUpdate = function() { var currenttime = $gVideo.attr('currentTime'); if(!seeksliding) $ghinda_video_seek.slider('value', currenttime); $ghinda_video_timer.text(gTimeFormat(currenttime)); }; $gVideo.bind('timeupdate', seekUpdate);

Here we're using the seekUpdate function to get the currentTime attribute of the video, and the gTimeFormat function to format the actual value received.

For the volume controls, we'll also use the jQuery UI slider and a custom function on the volume button for muting and un-muting the video.

$ghinda_volume.slider({ value: 1, orientation: "vertical", range: "min", max: 1, step: 0.05, animate: true, slide:function(e,ui){ $gVideo.attr('muted',false); video_volume = ui.value; $gVideo.attr('volume',ui.value); } }); var muteVolume = function() { if($gVideo.attr('muted')==true) { $gVideo.attr('muted', false); $ghinda_volume.slider('value', video_volume); $ghinda_volume_btn.removeClass('ghinda-volume-mute'); } else { $gVideo.attr('muted', true); $ghinda_volume.slider('value', '0'); $ghinda_volume_btn.addClass('ghinda-volume-mute'); }; }; $ghinda_volume_btn.click(muteVolume);

Finally we're going the remove the controls attribute from the <video>, because by this point our own custom controls are set up and we want to use those instead of the browser defaults.

$gVideo.removeAttr('controls');

Now that we have our plugin all done, we can call it on any video element we want, like so.

$('video').gVideo();

This will call the plugin on all the video elements on the page.

Look and Feel

And now for the fun part, the look and feel of the video player. Once the plugin is ready, customizing the controls is really easy with a little bit of CSS. As you've notice we haven't added any styling to the controls. We'll use CSS3 for all the customizations regarding the player.

First, we'll add some style to the main video player container. We'll use this as the main chrome for the player.

.ghinda-video-player { float: left; padding: 10px; border: 5px solid #61625d; -moz-border-radius: 5px; /* FF1+ */ -ms-border-radius: 5px; /* IE future proofing */ -webkit-border-radius: 5px; /* Saf3+, Chrome */ border-radius: 5px; /* Opera 10.5, IE 9 */ background: #000000; background-image: -moz-linear-gradient(top, #313131, #000000); /* FF3.6 */ background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #313131),color-stop(1, #000000)); /* Saf4+, Chrome */ box-shadow: inset 0 15px 35px #535353; }

We've floated it left, to prevent it from expanding to the full width of the player, instead keeping it restrained to the width of the actual video element. We're using gradients and border radius to add polish, plus an inset box shadow to emulate the gradient effect in Opera, as it does not yet support gradients (as of 10.60, the latest version at the time of writing).

Next we'll float all the controls to the left, to align them horizontally. We'll use opacity and transitions on the Play/Pause and Volume Mute/Unmute buttons to create a nice hover effect.

.ghinda-video-play { display: block; width: 22px; height: 22px; margin-right: 15px; background: url(../images/play-icon.png) no-repeat; opacity: 0.7; -moz-transition: all 0.2s ease-in-out; /* Firefox */ -ms-transition: all 0.2s ease-in-out; /* IE future proofing */ -o-transition: all 0.2s ease-in-out; /* Opera */ -webkit-transition: all 0.2s ease-in-out; /* Safari and Chrome */ transition: all 0.2s ease-in-out; } .ghinda-paused-button { background: url(../images/pause-icon.png) no-repeat; } .ghinda-video-play:hover { opacity: 1; }

I'm sure you followed the JavaScript part carefully, and saw that we're adding and removing classes on the Play/Pause button depending on the state of the video(Playing/Paused). That's why the ghida-paused-button class overwrites the background property of the ghinda-video-play class.

Now for the sliders. As you saw before, we're using the jQuery UI slider control for both the seek bar and the volume level. This component has its own styles defined in jQuery UI's stylesheet, but we'll completely overwrite these to make the look of the slider more in keeping with the rest of the player.

.ghinda-video-seek .ui-slider-handle { width: 15px; height: 15px; border: 1px solid #333; top: -4px; -moz-border-radius:10px; -ms-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; background: #e6e6e6; background-image: -moz-linear-gradient(top, #e6e6e6, #d5d5d5); background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #e6e6e6),color-stop(1, #d5d5d5)); box-shadow: inset 0 -3px 3px #d5d5d5; } .ghinda-video-seek .ui-slider-handle.ui-state-hover { background: #fff; } .ghinda-video-seek .ui-slider-range { -moz-border-radius:15px; -ms-border-radius:15px; -webkit-border-radius:15px; border-radius:15px; background: #4cbae8; background-image: -moz-linear-gradient(top, #4cbae8, #39a2ce); background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #4cbae8),color-stop(1, #39a2ce)); box-shadow: inset 0 -3px 3px #39a2ce; }

Currently the volume slider is also visible at all times, positioned next to the volume button. We'll change this so the slider is hidden by default, and shows up only when we're hovering the Mute/Unmute button, to make it look a bit more dynamic and neater. Again, transitions are our answer here:

.ghinda-volume-box { height: 30px; -moz-transition: all 0.1s ease-in-out; /* Firefox */ -ms-transition: all 0.1s ease-in-out; /* IE future proofing */ -o-transition: all 0.2s ease-in-out; /* Opera */ -webkit-transition: all 0.1s ease-in-out; /* Safari and Chrome */ transition: all 0.1s ease-in-out; } .ghinda-volume-box:hover { height: 135px; padding-top: 5px; } .ghinda-volume-slider { visibility: hidden; opacity: 0; -moz-transition: all 0.1s ease-in-out; /* Firefox */ -ms-transition: all 0.1s ease-in-out; /* IE future proofing */ -o-transition: all 0.1s ease-in-out; /* Opera */ -webkit-transition: all 0.1s ease-in-out; /* Safari and Chrome */ transition: all 0.1s ease-in-out; } .ghinda-volume-box:hover .ghinda-volume-slider { position: relative; visibility: visible; opacity: 1; }

We're hiding the volume slider by default, and giving the volume container a small fixed height that just fits the width of the volume button. We're also assigning transitions to both.

When the volume button is hovered, its height increases via the specified transition; we then use the .ghinda-volume-box:hover .ghinda-volume-slider descendant selector to transition the volume slider into view.

With basic CSS knowledge and some new CSS3 properties, we've already created a nice interface for our player, it looks like Figure 2:

Video player screenshot

Figure 2: Our finished video player.

Themeing the player

As you probably noticed, when creating the jQuery plugin, we've defined a set of default options. These options are theme and childtheme, and can be changed when calling the plugin, allowing us to easily apply custom themes as desired.

A theme represents a completely new set of CSS rules for every single control. A child theme on the other hand is a set of CSS rules that builds upon the rules of an existing theme, adding or overwriting the "parent" theme's style.

We can specify both of there options or only one, when calling the jQuery plugin.

$('video').gVideo({ childtheme:'smalldark' });

In the above example code we are calling the plugin with the smalldark child theme specified. This will apply our default parent theme, and then apply our child theme over the top of it, overwriting a small portion of the rules set by the parent theme. See Figure 3 for the Smalldark theme in action.

Smalldark child theme

Figure 3: the Smalldark child theme in action.

You can check out the final video player example live to see both themes in action, or download the source code (8.5mb, ZIP file) and experiment with it further.

Summary

Building our own custom video player with HTML5 video, JavaScript and CSS3 is fairly easy. By using JavaScript only for the actual functionality of the controls, and CSS3 for everything that involves the look and feel of the player, we get a powerful, easily customizable solution.

Kategorien: Google Reader

// Canto.js: An Improved Canvas API

Javascript author extraordinaire David Flanagan released Canto.js recently, a lightweight wrapper API for canvas, introduced here and documented at the top of the source code. Example:

PLAIN TEXT JAVASCRIPT: canto("canvas_id").moveTo(100,100).lineTo(200,200,100,200).closePath().stroke();
 

Notice three things:

  • canto() returns an abstraction of the canvas - a "Canto" object.
  • As with jQuery and similar libraries, there's method chaining; each method called on a Canto also returns the Canto.
  • lineTo() has been extended to support multiple lines being drawn in a single call.

Instead of setting the ink properties and then painting it, you can do it all in one step:

PLAIN TEXT JAVASCRIPT: canto("canvas_id").moveTo(100,100).lineTo(200,200,100,200).closePath().stroke({lineWidth: 15, strokeStyle: "red"});
 

And plenty more syntactic sugar - check out the API in the source code comments. Sweet!

Thanks @pkeane.

Kategorien: Google Reader

// Do You Know How Slow Your Web Page Is?

The Web Timing draft specification presents a standard set of metrics for measuring web page load time across browsers. We’re happy to announce that in Chrome 6, web developers can now access these new metrics under window.webkitPerformance.
Measuring web page load time is a notoriously tricky but important endeavor. One of the most common challenges is simply getting a true start time. Historically, the earliest a web page could reliably begin measurement is when the browser begins to parse an HTML document (by marking a start time in a <script> block at the top of the document).
Unfortunately, that is too late to include a significant portion of the time web surfers spend waiting for the page: much of the time is spent fetching the page from the web server. To address this shortcoming, some clever web developers work around the problem by storing the navigation start time in a cookie during the previous page’s onbeforeunload handler. However, this doesn’t work for the critical first page load which likely has a cold cache.
Web Timing now gives developers the ability to measure the true page load time by including the time to request, generate, and receive the HTML document. The timeline below illustrates the metrics it provides. The vertical line labeled "Legacy navigation started" is the earliest time a web page can reliably measure without Web Timing. In this case, instead of a misleading 80ms load time, it is now possible to see that the user actually experienced a 274ms time. Including this missing phase will make your measurements appear to increase. It’s not because pages are getting slower – we’re just getting a better view on where the time is actually being spent.

Across other browsers: Web Timing metrics are under window.msPerformance in the third platform preview of Internet Explorer 9 and work is underway to add window.mozPerformance to Firefox. The specification is still being finalized, so expect slight changes before the browser prefixes are dropped. If you’re running a supported browser, please try the Web Timing demonstration and send us feedback.
Posted by Tony Gentilcore, Software Engineer
Kategorien: Google Reader

// Constructorification

... he he, I know the title could not be worst, but after my last post about Arrayfication I have thought: "... hey, the Thing.ify(object) could be more than handy in many occasions such mixins and duck typing ...".

So, let me introduce the Function.prototype method that nobody will ever use:

Function.prototype.ify = function (o) {
for (var
self = this,
p = self.prototype,
// find a fucking way to implement this in ES3
// ... uh wait, there's no way to implement
// this in ES3 ...
// https://bugzilla.mozilla.org/show_bug.cgi?id=518663
m = Object.getOwnPropertyNames(p),
i = m.length, n; i--;
) {
// methods only
m[i] = typeof p[n = m[i]] == "function" ?
"o." + n + "=p." + n + ";" : ""
;
}
m.push("return o");
return (self.ify = Function("p",
"return function " +
(self.name || "anonymous") + "fy(o){" +
m.join("") +
"}"
)(p))(o);
};

Since the function requires a Object.getOwnPropertyNames call for its prototype in order to be able to inject it's properties and methods in whatever object, the ify method is lazily assigned.
This code makes "Function.ification" easy so that precedent post could be summarized via:

Array.ify(
document.getElementsByTagName("*")
).forEach(function (node) {
// do stuff with node
});

and be performed at light speed every other time while it won't cost at all until it's performed on whatever constructor the first time only.

Well, at least the technique may result interesting, unfortunately without ES5 it's not possible to reproduce the same behavior without knowing in advance all possible keys part of the native prototype (it's possible for user defined ones tho)
Kategorien: Google Reader

// Firefox 4 Beta 2 is here – Welcome CSS3 transitions

As we have explained before, Mozilla is now making more frequent updates to our beta program. So here it is, Firefox Beta 2 has just been released, 3 weeks after Beta 1.

Firefox 4 Beta 1 already brought a large amount of new features (see the Beta 1 feature list). So what’s new for web developers in this beta?

Performance & CSS3 Transitions

The two major features for web developers with this release are Performance improvements and CSS3 Transitions on CSS3 Transforms.

This video is hosted by Youtube and uses the HTML5 video tag if you have enabled it (see here). Youtube video here.

Performance: In this new Beta, Firefox comes with a new page building mechanism: Retained Layers. This mechanism provides noticeable faster speed for web pages with dynamic content, and scrolling is much smoother. Also, we’re still experimenting with hardware acceleration: using the GPU to render and build some parts of the web page.

CSS3 Transitions on transforms: The major change for web developers is probably CSS3 Transitions on CSS3 Transformations.

CSS3 Transitions provide a way to animate changes to CSS properties, instead of having the changes take effect instantly. See the documentation for details.

This feature was available in Firefox 4 Beta 1, but in this new Beta, you can use Transitions on Transformation.

A CSS3 Transformation allows you to define a Transformation (scale, translate, skew) on any HTML element. And you can animate this transformation with the transitions.

See this box? Move your mouse over it, and its position transform: rotate(5deg); will transform transform: rotate(350deg) scale(1.4) rotate(-30deg); through a smooth animation. #victim { background-color: yellow; color: black;   transition-duration: 1s; transform: rotate(10deg);   /* Prefixes */   -moz-transition-duration: 1s; -moz-transform: rotate(5deg);   -webkit-transition-duration: 1s; -webkit-transform: rotate(10deg);   -o-transition-duration: 1s; -o-transform: rotate(10deg); } #victim:hover { background-color: red; color: white;   transform: rotate(350deg) scale(1.4) rotate(-30deg);   /* Prefixes */   -moz-transform: rotate(350deg) scale(1.4) rotate(-30deg); -webkit-transform: rotate(350deg) scale(1.4) rotate(-30deg); -o-transform: rotate(350deg) scale(1.4) rotate(-30deg); }

CSS 3 Transitions are supported by Webkit-based browsers (Safari and Chrome), Opera and now Firefox as well. Degradation (if not supported) is graceful (no animation, but the style is still applied). Therefore, you can start using it right away.

Demos

I’ve written a couple of demos to show both CSS3 Transitions on Transforms and hardware acceleration (See the video above for screencasts).

This demo shows 5 videos. The videos are Black&White in the thumbnails (using a SVG Filter) and colorful when real size (click on them). The “whirly” effect is done with CSS Transitions. Move you mouse over the video, you’ll see a question mark (?) button. Click on it to have the details about the video and to see another SVG Filter applied (feGaussianBlur). This page shows 2 videos. The top left video is a round video (thanks to SVG clip-path) with SVG controls. The main video is clickable (magnifies the video). The text on top of the video is clickable as well, to send it to the background using CSS Transitions. This page is a simple list of images, video and canvas elements. Clicking on an element will apply a CSS Transform to the page itself with a transition. White elements are clickable (play video or bring a WebGL object). I encourage you to use a hardware accelerated and a WebGL capable browser. For Firefox on Windows, you should enable Direct2D.

Credits

Creative Commons videos:

The multicolor cloud effect (MIT License)

Kategorien: Google Reader

// Array.prototype.slice VS Arrayfication

One of the most common operations performed on daily basis directly or indirectly via frameworks and libraries is Array.prototype.slice calls over non Array elements such HTMLCollection, NodeList, and Arguments.

Why We Perform Such Operation
The Function.prototype.apply works only with object created through the [[Class]] Array or Arguments.
In latter case we may like to avoid ES3 arguments and named arguments mess when dealing with indexes.
Finally, in most of the case we would like to perform Array operations over ArrayLike objects to filer, map, splice, change, modify, etc etc ...

The Slice Cost
Let's perform over an ArrayLike object of length 2000, 2000 slice calls (change the length if you have such powerful machine):

// create the ArrayLike object
for(var arguments = {length:2000}, i = 0; i < 2000; ++i)
arguments[i] = i;
;

// define the bench function
function testSlice(arguments) {
var t = new Date;
for (var slice = Array.prototype.slice, i = 0, length = arguments.length; i < length; ++i)
slice.call(arguments);
;
return new Date - t;
}

// test it
alert(testSlice(arguments));

The average time in my Atom N270 based Netbook is 1750 ms, and numbers are not that unreasonable.
While a list of 2000 generic values may be not that common, the number of slice.call may be definitively more than 2000 during an application life cycle. All this wasted time to simply transform a generic list into an Array? And maybe just to loop and re-loop over it to filter or change values and indexes?

Alternative One: __proto__
If we modify the __proto__ property of whatever object and in almost all browsers (not IE, of course), we can somehow "promote" the current object to Array, except for the [[Class]] that will still be the generic Object, or Arguments.
The undesired side effect is that the modified object won't find anymore in its prototype its original methods, so we can define this technique really greedy.
But what about performances?

// function to test
function testProto(arguments) {
var t = new Date;
for (var proto = Array.prototype, i = 0, length = arguments.length; i < length; ++i)
arguments.__proto__ = proto;
;
return new Date - t;
}

// the result using precedent arguments object
alert(testProto(arguments));

The average elapsed time in this case is 40 ms but we have to remember is that we are not converting the object into an Array instance, we are simply overwriting it's inherited properties and methods with those part of the Array.prototype object.
This means that push, unshift, splice, forEach, or other operations, will be accessible directly through the object (e.g. arguments.forEach( ... ))
If these methods are the reason we would like to slice the generic object, this solution is definitively preferred.

Alternative Two: Arrayfication
To avoid the undesired side effect obtained via __proto__ assignment, the removal of inherited methods, we may consider to use call or apply directly via Array.prototype.
The imminent side effect of this technique is that potentially every function may like to use one of the Array prototype methods against the same object which is always passed by reference.
A simple solution could be the one to attach directly a method to this object, so that every part of the application will be able to use, as example, a forEach call for this object, without accessing every time the Array.prototype.forEach method.

arguments.forEach = Array.prototype.forEach;
// now use forEach wherever we need
// with arguments object

Since every function may like to use one or more Array methods, how about creating a function able to attach all of them in one shot?

Array.fy = (function () {
// (C) WebReflection - Mit Style License
for (var
m = [
"pop", "push", "reverse", "shift", "sort", "splice", "unshift",
"concat", "join", "slice", "indexOf", "lastIndexOf",
"filter", "forEach", "every", "map", "some", "reduce", "reduceRight"
],
i = m.length; i--;
) {
m[i] = "o." + m[i] + "=p." + m[i];
}
m.push("return o");
return Function("p",
"return function Arrayfy(o){" + m.join(";") + "}"
)(Array.prototype);
}());

With a single call we can attach all current available Array.prototype methods once without getting rid of current inherited properties or methods.
Let's see how much does a call cost:

// test function for Array.fy
function testArrayfy(arguments) {
var t = new Date;
for (var fy = Array.fy, i = 0, length = arguments.length; i < length; ++i)
fy(arguments);
;
return new Date - t;
}

// bench
alert(testArrayfy(arguments));

The average elapsed time for this operation is 3 ms.
After a single call we can consider the generic object an Array duck, preserving its inheritance.
The greedy aspect is about possible overwrites, but I have personally never called a method forEach if this is not exactly representing the Array.forEach method.

Arrayfied Operations
The last benchmark we can do is about common Array operations over our Arrayfied object.
The first consideration to do is that slice, as every other Array operation, seems to be extremely optimized for real Array objects.
In few words if we need to transform because we need many calls to forEach, filter, map, slice, etc, the transformation via slice is probably what we are looking for.
But if we need a generic loop over a generic callback and just few times, Array.fy proposal is probably the most indicated one. Here some extra test:

// slice plus a forEach operation
function testSliceEach(arguments) {
var t = new Date;
for (var slice = Array.prototype.slice, fn = function() {}, i = 0, length = arguments.length; i < length; ++i)
slice.call(arguments).forEach(fn);
;
return new Date - t;
}

// just forEach through Arrayfied object
function testArrayfied(arguments) {
var t = new Date;
Array.fy(arguments);
for (var fn = function() {}, i = 0, length = arguments.length; i < length; ++i)
arguments.forEach(fn);
;
return new Date - t;
}

// just slice through Arrayfied object
function testArrayfiedSliced(arguments) {
var t = new Date;
Array.fy(arguments);
for (var fn = function() {}, i = 0, length = arguments.length; i < length; ++i)
arguments.slice();
;
return new Date - t;
}

// bench

alert(testSliceEach(arguments)); // 3200ms
alert(testArrayfied(arguments)); // 2400ms
alert(testArrayfiedSliced(arguments));// 1700ms

The last test is against a classic slice.call and it costs basically the same.
First and seconds demonstrate that if we slice to use native power we are actually spending more time than using native power directly.
Bear in mind that if the variable is already an Array, slice will cost much less and the average against the last test will be 1350 ms.

IE And Conclusions
I keep saying that IE should simply have normalized Array.prototype, ignoring those person that wrongly rely in for in loops over arrays when it's not necessary, and making this Array.fy portable for IE world as well since the internal proto variable is a pointer to the original Array.prototype then automatically ready for natives standard enhancements.
The nice part is that rather than see Array.prototype.something.call in every piece of code we can easily use one fast call to have them all ... so, you decide :-)

.. last minute Example ...
Just because sometimes we lack of fantasy, here a generic usage for Array.fy:

function $(selector, parentNode) {
return Array.fy((parentNode || document).querySelectorAll(selector));
}

$("div").forEach(function (div, i, nodeList) {
div.innerHTML = "Array.fy rocks!";
});
Kategorien: Google Reader

// YUI 3.2.0 Preview Release 1: Touch Event Support, Gestures, Transitions, CSS Grids, ScrollView, Uploader, and More

The YUI contributor’s team is pleased to announce the first developer preview of the upcoming YUI 3.2.0 release. This preview provides an opportunity for developers and implementers to help test the release for potential regressions and to provide feedback on new features and components. If you have an existing YUI implementation, please exercise YUI 3.2.0pr1 in your development environment and let us know what you find.

There are three ways to get started with the preview release:

  • Use from the CDN: YUI 3.2.0pr1 is available on the CDN via the 3.2.0pr1 version tag — so you can reference preview-release files like http://yui.yahooapis.com/combo?3.2.0pr1/build/yui/yui-min.js. If you switch to this seed file for the preview release, all subsequent use() statements will continue to load YUI 3.2.0pr1.
  • Download the release: Download YUI 3.2.0pr1 from YUILibrary.com, including source code and examples for all components — including those new to this release.
  • Explore the examples: As a convenience, we’ve posted the preview (along with the functioning examples roster) to YUIBlog. Feel free to explore the release there as a prelude to switching your CDN version reference (or downloading the preview) and testing it out in your own environment.
Noteworthy Changes Coming in YUI 3.2.0

As with all YUI development work, you can track our current plans and progress on our YUI 3 tasklist, including a comprehensive list of YUI 3.2.0 (and some upcoming 3.3.0) changes; you can also check in on our progress addressing issues in the bug database. Here are some of the new and updated components featured in the 3.2.0 developer preview:

  • Intrinsic support for touch events has been added (mynode.on("touchstart", function(e) {});). We’ve also added a Gestures module with two bundled gestures — gesture-flick and gesture-move — that work with both touch- and mouse-driven devices. Check out the API docs or the bundled sample page for ideas about how to start using Gestures.
  • YUI’s intrinsic Loader now supports capability-based loading. This allows us to segregate, for example, IE-specific code into separate submodules and allow the Loader to bundle that code only for browsers that require it. We’re leveraging this new feature to avoid shipping IE-specific code in the Dom module to non-IE browsers, a performance/k-weight boost that will benefit all users of modern browsers with no code change required.
  • YUI 3’s animation portfolio now supports transitions via the Transition module, providing browser normalization for this powerful, hardware-accelerated (where available) technique for handling transitions; check out the example for sample code. Animation, in its most basic form, has a streamlined dependency tree for modern browsers, significantly reducing the k-weight for simple animation in better browsers.
  • YUI 3.2.0 will bring with it a new beta version of YUI’s CSS Grids component, and you can begin exploring this new approach to Grids in the preview release. The examples are the best place to start.
  • We worked with Michael Johnston of the Yahoo! Mobile Engineering team to bring a new (beta) ScrollView widget to YUI 3.2.0. ScrollView provides a scrolling pane implementation familiar to users of native Apple iOS applications, emulating the elasticity of the element when scrolled to the beginning or ending limit. You’ll see in the 3.2.0pr1 examples for ScrollView that this component is device neutral, working well with a mouse as well as with touch events on your Android or iOS device.
  • The Uploader component from YUI 2 is now part of the YUI 3 family as well, debuting as a beta in 3.2.0.
  • The History module that debuted with YUI 3.0.0, which was a port of the YUI 2 version, has been deprecated (it remains available in YUI 3.2.0 as history-deprecated). A new beta History utility debuts in 3.2.0, based on Ryan Grove’s History Lite module from the YUI 3 Gallery. A preview-release example from the new component is a good starting reference.
  • The JSONP and YQL Query modules from the YUI 3 Gallery have become canonical components, debuting as beta in this release.
Feedback

The goal of a preview release is to make it as easy as possible for all of us in the community to evaluate progress of the upcoming release and provide feedback. Please take some time to test 3.2.0pr1 and let us know what you find by filing tickets in the YUI 3 bug database marked as “Observed in version” 3.2.0pr1. We’ll do our best to address preview-release questions on the YUI 3 Forums, too.

Kategorien: Google Reader

// JavaScript Minification Part II

Variable naming can be a source of coding angst for humans trying to understand code. Once you’re sure that a human doesn’t need to interpret your JavaScript code, variables simply become generic placeholders for values. Nicholas C. Zakas shows us how to further minify JavaScript by replacing local variable names with the YUI Compressor.contact.us@alistapart.com (Nicholas C. Zakas)166702322456877685611736528485931647586201650999374317979751068689244044986337650476611736287053283011731391817765969451103501049211940809220771206984318013287815167073887160809467060936933914334987521263596504213267338000458366911360432541061966480780391876320995854365075818768000518313665720447865
Kategorien: Google Reader

// SVG with a little help from Raphaël

Want to make fancy, interactive, scalable vector graphics (SVGs) that look beautiful at any resolution and degrade with grace? Brian Suda urges you to consider Raphaël for your SVG heavy lifting.contact.us@alistapart.com ( Brian Suda)094236590523611685521282789693559354686014048597963530591234027585087650165594111574835800734783436717365284859316475862005749301212565817740476611736287053283009552507979975981384120347003627250743400929871196365159880710350104921194080922160092074003788812280730941313983468223003343349680384261950060936933914334987521602820473884831723312635965042132673380088531617041740640290641551774625972819605221790502551658316061966480780391876321714712376642589131800518313665720447865
Kategorien: Google Reader
Inhalt abgleichen

// My tweets