DCSIMG
Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2011 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Getting Started with IndexedDB Article

Getting Started with IndexedDB Article

Getting Started with IndexedDB ArticleI’ve started to write a Blog post about IndexedDB and it was too long so I decided to post it as article in The CodeProject web site. The article name is “Getting Started with IndexedDB”.

If you want to start using the IndexedDB JavaScript API, to store data on the client-side and to save round-trips to the database on the server-side the article is for you.
You can read the article here.

Enjoy!

Working with Inline Web Workers

Working with Inline Web Workers

Working with Inline Web WorkersIn the past I wrote a post about what are Web Workers. In short, Web Workers enable web developers to run JavaScript code in the background which might help to increase web page performance. This post is going to explain what are inline Web Workers and how to create them.

Inline Web Workers

When dealing with Web Workers, most of the times you will create a separate JavaScript file for the worker to execute. Inline Web Workers are Web Workers which are created in the same web page context or on the fly. The reason for doing such a thing is obvious, sometimes we want to reduce the number of requests that the page perform and sometimes we need to create some functionality on the fly. Executing external JavaScript files can’t help us with that.

There are two kinds of inline Web Workers:

  • Page inline worker – The worker's JavaScript code is created inline inside the web page. In this case you will use a script tag with an id and a javascript/worker type. the type will indicate to the browser not to parse the written inline JavaScript and it will refer to it as string. Here is an example for such script tag:
    <script id="worker" type="javascript/worker">
       postMessage('worker sent message');
    </script>
    Later you will be able to retrieve the script by its id and use its textContent property to extract the worker body.
  • On the fly worker – The worker’s JavaScript code is provided by an external source as string.

In both of the cases, in order to run the worker you will have to create a blob object and a blob URL.

Creating the Web Worker

The main way to create an inline Web Worker is using the BlobBuilder object which was added by the HTML5 File API. The BlobBuilder enables us to create a blob object from a given string. It includes two main functions – the append function and the getBlob function. The append function adds data into the underlining blob and the getBlob returns the created blob object.

After you create a blob object from the inline worker implementation you will have to create a URL from it. The reason is that Web Workers gets a URL as parameter. For our rescue, HTML5 defines another two functions in the File API – createObjectURL and revokeObjectURL. Both of the functions exists in the window.URL object. Blob URLs are a unique URL which is created and stored by the browser up until the document is unloaded. The createObjectURL function gets a blob object and returns the blob URI which can be used. The revokeObjectURL function is used to release a created blob URL. If you are creating a lot of blob URLs you should use the revokeObjectURL in order to release references to blob URLs which aren’t in use.

Lets take a look at an example of creating an inline Web Worker:

var bb = new BlobBuilder();
bb.append(workerBody);
var workerURL = window.URL.createObjectURL(bb.getBlob());
var worker = new Worker(workerURL);

In the example a BlobBuilder is created and a workerBody is appended to it. The workerBody can be any piece of code that you want to run inside a Web Worker. After you create the in-memory blob you will use the createObjectURL function to create the the blob URL and use it as a parameter to the Web Worker. If you want to use the script tag from the first code example you can write the following code:

var bb = new BlobBuilder();
bb.append(document.querySelector('#worker').textContent);
var workerURL = window.URL.createObjectURL(bb.getBlob());
var worker = new Worker(workerURL);

The Full Example

I wanted to create an experimental code example to show how to encapsulate the previous inline Web Workers implementation inside a JavaScript object and use it so here it goes:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Inline WebWorker</title>
    <meta charset="utf-8" />
    <script>
        // create a namespace for the object
        var workerHelpers = workerHelpers || {};
        
        // set the blob builder and window.URL according to the browser prefix if needed
        var BlobBuilder = BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
        window.URL = window.URL || window.webkitURL;
 
        workerHelpers.InlineWorkerCreator = function () {
        };
 
        workerHelpers.InlineWorkerCreator.prototype = function () {
            createInlineWorker = function (workerBody, onmessage) {
                if (BlobBuilder) {
                    var bb = new BlobBuilder();
                    bb.append(workerBody);
 
                    var workerURL = window.URL.createObjectURL(bb.getBlob());
                    var worker = new Worker(workerURL);
                    worker.onmessage = onmessage;
                    return workerURL;
                }
                else {
                    console.log('BlobBuilder is not supported in the browser');
                    return;
                }
            },
            releaseInlineWorker = function (workerURL) {
                window.URL.revokeObjectURL(workerURL);
            };
 
            return {
                createInlineWorker: createInlineWorker,
                releaseInlineWorker: releaseInlineWorker
            };
        } ();
 
        window.addEventListener('DOMContentLoaded', function () {
            var creator = new workerHelpers.InlineWorkerCreator();
            var workerURL = creator.createInlineWorker('postMessage(\'worker sent message\');', function (e) {
                console.log("Received: " + e.data);
            });
            console.log(workerURL);
 
            // release the URL after a second
            setTimeout(function () { creator.releaseInlineWorker(workerURL); }, 1000);
        }, false);        
    </script>
</head>
<body>
</body>
</html>

Summary

In the post I explained the reason to create inline Web Workers. I also showed how to create an inline Web Worker and provided an implementation for a JavaScript object that can be used to do that. 

I’ll appreciate any comments about the provided code.

Quick Tip – JavaScript Namespaces

Quick Tip – JavaScript Namespaces

Namespaces (or named scopes) are widely used in many programming languages. Namespaces help to group a set of identifiers into a logical group. An identifier can be a named class, named interface or any other language element that is contained inside the namespace. Since the same identifier can be used in more than one namespace but with a different meaning, using namespaces can help reduce name collisions.

Creating a JavaScript Namespace

JavaScript doesn’t include namespaces. On the other hand, JavaScript includes function scopes which means that every function which is created in the JavaScript global scope holds its own scope. With this information in mind, we can mimic namespace scope by creating a function scope. Doing so will help to reduce the number of objects associated with the global scope and help to avoid collisions between identifiers created for an application when using external libraries for example. Here is an example of creating a JavaScript namespace using a function scope:

var ns = ns || {};

The code uses a simple check whether the namespace was declared previously. If the namespace was declared the left side of the statement is evaluated and the ns variable will include the previously defined namespace. If the namespace wasn’t declared previously a new object literal (which is another way to create a function in JavaScript) will be created and be set to the ns variable.

Using a JavaScript Namespace

In the previous example a namespace was declared. In order to use the namespace you will use its name and create objects/functions inside of it. Here is an example of setting a simple object inside of the previously created namespace:

ns.Game = function (id, name, description) {
    this.id = id;
    this.name = name;
    this.description = description;
};

Now if you want to use the Game object you will create it using its namespace and it name. Here is an example for that:

var game = new ns.Game(1, 'Kinectimals', 'Raise your own cub inside this popular Kinect game');

Summary

Namespaces in JavaScript can help to organize your code into more logical groups/modules. One aspect of using this method is the reducing of objects inside the JavaScript global scope.

Posted: Jan 27 2012, 04:40 PM by Gil Fink | with no comments |
תגים:,

Build Modern Web Applications with HTML5, CSS3 and JavaScript Session – Round Three

Build Modern Web Applications with HTML5, CSS3 and JavaScript Session – Round Three

Build Modern Web Applications with HTML5, CSS3 and JavaScript Session – Round ThreeOn October 31 and December 26 last year, I delivered the “Build Modern Web Applications with HTML5, CSS3 and JavaScript” MSDN session. Since both of the sessions were fully booked, I’m going to deliver the same session on February 9 at Microsoft HQ and give those who didn’t attended in the previous sessions the opportunity to hear it. If you are interested in HTML5 you can register here.

See you there!

I’m Back

I’m Back

If you are following my Blog, you could see that in the last couple of weeks I disappeared a little. This post is being written just to let you know that I’m fine and returned to work after two weeks “vacation”. I’ll return writing posts about development soon so stay tuned.

As always, if you need my assistance you can contact me through my blog, my twitter account, or send me an email through the blog’s contact form. I’ll do my best to answer every question that you ask even if the answer is I don’t know...

Posted: Jan 19 2012, 03:54 PM by Gil Fink | with no comments |
תגים:

The async and defer Script Attributes in HTML5

The async and defer Script Attributes in HTML5

The async and defer Script Attributes in HTML5One of the rules of thumb that you always hear regarding script elements is to put them very close to the </body> closing tag of the Web page. The main reason for that is that script elements are fetched and executed immediately when the browser encounter them. This default behavior includes blocking the browser’s rendering, loading a JavaScript file into memory, and executing its code immediately. In many circumstances, and in particular when large JavaScript files are involved, this might create a performance bottleneck.

One of the solutions for this problem is to use script tag injections or other Ajax techniques to prevent the browser from blocking. That might help to increase performance but it requires more coding and testing and in some occasions might create bugs because it is very hard to synchronize the file loading and executioning.

HTML5 introduces the async script attribute which helps to load scripts asynchronous. In the specifications you can also find another attribute, the defer attribute, that is very similar to the async attribute but it has another purpose. Both of the attributes will be presented in this post.

The async Attribute

The async attribute was introduced in HTML5. Its purpose is to signal the browser that a script should be executed asynchronously, and as soon as it is available. This means that when a browser encounter a script tag with the async attribute, it will download the script asynchronous and not block the rendering process. At the first opportunity after the script finished downloading and before the window’s load event the browser will execute the script. Here is how you will use the async attribute:

<script src="jsFile.js" async></script> 

The async attribute can be used only on script element that point to external JavaScript file. That means that the src attribute must exists when you use the attribute. Also, you can’t know the execution order of scripts that use the async attribute.

In most of the major browsers, such as Chrome, Firefox, and Opera, the attribute is available for use. IE9 and previous versions of IE don’t support the attribute yet.

The defer Attribute

The defer attribute is not new in HTML5. It can be found in most of the browser (even in very early versions of IE). Its purpose is to signal the browser that a script should be executed in parallel and without stopping the page’s rendering. Deferred scripts guaranteed to run in sequence in the order that they are written in the code. They are executed before the DOMContentLoaded event. Here is an example of using the defer attribute:

<script src="jsFile.js" defer></script>

As in the async attribute, defer attribute can be used only on script element that point to external JavaScript file.

Pay attention not to use the defer attribute on external script files that use the document.write or generate document content.  

What happens if you add both of the attributes to a script element?
Here is the answer in the specifications:
“The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.”

Summary

The post introduced the async and defer script attributes. Both of them can be used to improve the performance of Web pages because they help to load scripts asynchronous without blocking the page rendering. In most of the times you will use the attributes instead of writing your script elements in the bottom of the Web page.

Build Modern Web Applications with HTML5 CSS3 and JavaScript – Slide Deck and Demos

Build Modern Web Applications with HTML5 CSS3 and JavaScript – Slide Deck and Demos

Build Modern Web Applications with HTML5, CSS3 and JavaScript Session Slide Deck and DemosToday, I delivered a second round of my HTML5 MSDN session at Microsoft HQ. I want to thank all the attendees who attended and heard about the transition that the web eco-system is going through. The session agenda was as follows:

  • What is HTML5?
  • The New Elements
  • Migration to HTML5
  • HTML5 APIs (Canvas, Web Storage, AppCache, Geolocation and Web Workers)
  • CSS3

The slide deck and demos can be downloaded from here.

Enjoy!

CSS3 2D and 3D Transform

CSS3 2D and 3D Transform

CSS3 2D and 3D TransformWhen I first encountered CSS3 transform property, I had a nostalgic moment that took me back to the days that I was a computer science student. Back then, one of the mathematics courses that I had to take was linear algebra. Linear algebra deals with vector spaces and linear functions that make transformations using vectors and matrixes. The course itself wasn’t so hard but later on, when I started to work as a Web developer, I always thought to myself were can I use those pesky vectors and matrixes in a Web site or application without any plugins. Now with CSS3 transform I got the an answer.

CSS3 Transform

Using the new CSS3 transform property you can create element transformations and to change the shape, size and position of the element. The transform property can get a set of transformation functions which can be composed if you write them separated by whitespace.
The 2D transform functions included:

  • translate – given left and top parameters, the element will move from its position to the new point. There are also a translateX and translateY functions that get only one parameter and translate the element only in one axis.
  • rotate – given a degree the element rotate clockwise according to the degree. Pay attention that the parameter should be in a specific format for example these are valid parameters: 60deg, 80deg and etc.
  • scale – given a width and height, the element will increase or decrease its size. There are also scaleX and scaleY functions that get only one parameter and scale the element only in one axis.
  • skew – given x degree and y degree parameters, the element will turn in the given angles first in the x-axis and then in the y-axis. There are also skewX and skewY functions that get only one parameter and skew the element only in one axis.
  • matrix – given six a-f parameters apply the transformation matrix [a b c d e f] on the element.

The 3D transform functions included:

  • matrix3d – the same as the matrix function but now gets 16 parameters.
  • translate3d – gets an additional z-axis parameter.
  • scale3d – gets an additional z-axis parameter. There is also scaleZ function that scale the element only in the z-axis.
  • rotate3d – gets four parameters – x, y and z that define the [x y z] direction vector and a degree to rotate in that direction. There is also a rotateZ function that rotate the element in the z-axis.

A Simple Transform Example

Using the transform property is simple as to set every other CSS property on an element. Here is a simple example of how to use the transform property:

<!DOCTYPE html>
<html>
<head>
    <title>Transformation Example</title>
    <style type="text/css">               
        #rotatedTriangle 
        {     
            position:absolute;
            left: 100px;
            top:100px;          
            height: 100px; 
            width: 100px;            
            background-color: Green;            
            transform: rotate(45deg) scale(2, 2);                      
        }
    </style>
</head>
<body>
    <div id="rotatedTriangle"></div>
</body>
</html>

Pay attention – I use the specification CSS properties. In every major browser up until the specification become recommendation you will have to use the browser prefix.

Here is a picture of the outcome of the transformation in the Web page:
Transform Example

Combining CSS3 Transform and CSS3 Animations

In a previous post I wrote about CSS3 animations and how to use it to create simple animations. You can combine the knowledge of CSS3 animations with CSS3 transform in order to create sophisticated animations embedded in your Web pages. Lets see a simple example:

<!DOCTYPE html>
<html>
<head>
    <title>Transformation and Animation</title>
    <style type="text/css">
        @keyframes trans 
        {   
            from { transform: translate(0px, 0px) scale(1, 1); }               
            to { transform: translate(300px, 300px) scale(2, 2); }
        }
        
        #animatedDiv 
        {     
            position:absolute;
            left: 100px;
            top:100px;          
            height: 100px; 
            width: 100px;            
            background-color: Green;            
            animation: trans 5s linear 1s infinite;            
        }
    </style>
</head>
<body>
    <div id="animatedDiv"></div>
</body>
</html>

In the example I use the @keyframes rule to apply the translate and scale function on a div element embedded in the Web page. The animation will translate the div 300px in the x-axis and y-axis and then it will scale the div twice its size. This is a simple example but it shows the concept of using two CSS3 modules to get a very interesting outcome.

Pay attention – I use the specification CSS properties. In every major browser up until the specification become recommendation you will have to use the browser prefix.

Summary

CSS3 transform helps to create element transformations in 2D and 3D. Using this new CSS3 module can help to create graphics and of course animations which could be achieved in the past only with plugins or with a lot of JavaScript code. Not all the browsers support the transform property but you can use fallbacks in order to implement it even today.

Posted: Dec 22 2011, 08:33 AM by Gil Fink | with no comments |
תגים:, ,

CSS3 Animations

CSS3 Animations

CSS3 AnimationsLately I’m involved in a very interesting HTML5 project which I’ll tell about in the future. Meanwhile, I get to “play” with HTML5 and CSS3 specifications. One of the new interesting CSS3 specifications is probably the CSS3 animations. Does these things ring a bell – animated images, simple animation with Flash or JavaScript. If so, this post is for you.

Why to Use Animations?

Most of the Web sites and applications today use animations. You can find them in marketing ads embedded inside a site, in animated images while waiting for something like download to finish and in many other places. The added value of animation is that it draws the user’s attention. This is also its drawback since over using animations can cause distraction and might draw users from the Web site or application. In the past if you wanted to use animations you could use animated images, Flash or JavaScript. Today with HTML5 that isn’t necessary. You can use Canvas, SVG or even CSS to achieve the same results.

What is CSS3 Animations?

CSS3 introduces a new CSS module which is called CSS Animations Module Level 3. The module describe how to create simple animations using CSS3 new properties. CSS3 animations are defined with a new @keyframes rule which define the frames of the animation. Combined with the animation properties you can achieve simple animations that are composed of style changes only.

Defining the Animation

In order to define the animation, you will use the @keyframes rule and give it a meaningful name. Inside the @keyframes block you must specify a starting and ending point for the animation. You do that using 0% or from value for the starting point an 100% or to value for the ending point. You can also create frames by specifying their percentage in the animation itself. Here is a simple animation definition:

@keyframes changeBackground 
{
   from { background-color: white; }
   50% { background-color: green; }
   to {background-color: white; }
}

The animation here just change the background from white to green during the running of the animation. You can use any CSS property to create your animations.
defining the animation isn’t sufficient since it does nothing. In order to run the animation you will use the animation properties to set it to a DOM element.

The animation Properties

There are a set of animation functions that are specified in the specification such as animation-name and animation-duration. I prefer to use the shorten animation property that include those functions. The animation property gets 6 different parameters which are name, duration, timing function, delay, iteration count and direction. If the duration is omitted than its default value is 0 and the animation won’t run. Also if the name is ‘none’ value that will stop a running animation. Here is an example of setting the animation property on some element with the animatedDiv id:

#animatedDiv
{
   animation: changeBackground 2s linear 1s infinite alternate;
}

The animation will run the animation that was defined earlier, for 2 seconds duration, with a linear timing function, with a delay of 1 second, infinite and the direction will be alternate.

Pay attention that most of the browsers added CSS3 animation with their prefix so the previous code won’t work in all browsers. For example, Chrome uses the @-webkit-keyframes rule and the –webkit-animation property prefixes.

Summary

CSS3 animations can help to reduce the use of animated images and the use of plug-ins for simple animation. It define a simple animation model which can be set by defining the animation with the @keyframes rule and using them on elements with the animation properties.

Posted: Dec 14 2011, 03:23 PM by Gil Fink | with 2 comment(s) |
תגים:, ,

Keep Users Coming Back With Desktop Notifications for Web Apps Article

Keep Users Coming Back With Desktop Notifications for Web Apps Article

Keep Users Coming Back With Desktop Notifications for Web Apps ArticleA few days ago, an article I wrote for DZone web site was published in their HTML5 Microzone. The article is called “Keep Users Coming Back With Desktop Notifications for Web Apps” and it discusses desktop notifications and in particular IE9 Pinned Sites and HTML5 Notification API.
You can read the article here.

Enjoy! 

SDP11 My Tutorial Days Demos

SDP11 My Tutorial Days Demos

SDP11 My Tutorial Days Demos

Sela SDP11 is over.
Here are some photos that my colleagues caught me talking during the conference:

SDP1SDP2

I want to thank all the attendees who attended the two tutorial days that I delivered:

As promised, I uploaded all the demos from the tutorials to my SkyDrive and you can download it from here.
See you in the next SDP.

Build Modern Web Applications with HTML5, CSS3 and JavaScript Session – Round Two

Build Modern Web Applications with HTML5, CSS3 and JavaScript Session – Round Two

Build Modern Web Applications with HTML5, CSS3 and JavaScript Session – Round TwoOn October 31, I delivered the “Build Modern Web Applications with HTML5, CSS3 and JavaScript” MSDN session. I’m going to deliver the same session on December 26 at Microsoft HQ. If you are interested in attending the session you can register here.

See you there!

Sela SDP Returns

Sela SDP Returns

SDPLogo

Between 4 to 8 of December, Sela Group is having its annual SDP (Sela Developer Practice) conference. In this 5 days conference there will be 18 tutorial days with 22 experts about the hottest Microsoft technologies. In the conference I’m taking part in two tutorial days:

  • HTML5 -
    HTML is the markup language that every web developer uses to structure and present content in the Internet. HTML5 is the standard that is being shaped and developed currently. It extends and improves the last HTML4 standard and takes it to the next level with multimedia, communication support and more. In this one day tutorial you will get to know what is HTML5 all about and how you can use it even now in your web applications or sites.
  • Deep Dive into JavaScript (co-presenting with Elad) –
    JavaScript is gaining a lot of attention lately with the rise of HTML5 and with the latest news from Microsoft that it will become a first class citizen in Windows 8. During the last years a very big eco-system with a lot of libraries and tools was built around it. In this deep dive tutorial we will discuss jQuery, Knockout.js and other libraries which help you build RIA applications with JavaScript. We'll also dedicate some time to the future directions of client technologies. 

See you there!

Back to Basics – JavaScript onerror Event

Back to Basics – JavaScript onerror Event

The JavaScript window.onerror event is a very useful event that I find very strange that sometimes client-side developers don’t know. The event is fired most of the times (yep not every time) an error occurs in a JavaScript code. You can wire a handler to the event that will help you to prevent errors from bubbling to the browser or to send the errors to some logger for further investigation.

The onerror Event

The window.onerror is an event handler for error events that are sent to the window. It isn’t supported in all the browsers (mostly in old browsers) so you can’t take it for granted that it will work but most of the time it will. It takes 3 optional parameters:

  • An error message 
  • A Url where the error was raised 
  • The line number of the line that raised the error

Here is a simple code sample which will suppress most of the raised JavaScript errors:

window.onerror = function(msg, url, lineNumber) {   
    return true; // prevents browser error messages  
};  

While the previous code will stop the bubbling of the errors to the browser, I prefer to do more than just preventing the annoying browser error dialogs. You can add an Ajax call in order to send the error to a logger that is sitting on your site. This will help you to monitor and diagnose JavaScript errors and will help you to fix JavaScript bugs.

Summary

The onerror event handler can be very useful and might help to prevent the browser JavaScript error dialogs. Even so, you might be careful when using it since not all of the browsers support it. Combining it with logging framework such as Log4js, log4javascript or just plain Ajax functionality for logging might help you to monitor the JavaScript errors in your web site/application.

HTML5 and Government Organizations Session Recording

HTML5 and Government Organizations Session Recording

HTML5 and Government Organizations Session RecordingA month ago I had the pleasure to deliver a session in the HTML5Fest conference. The session’s subject was about HTML5 and government organizations. A few days ago the recording of the session was uploaded to the conference’s site. If you like to hear that session (in Hebrew) you can go to this link.

Enjoy!

More Posts Next page »