Preloading images before page onload using css and js

css:

body:after
{
content: url(‘../../img/spinner/b.webp’);

}

 

js/ajax:

window.onload = function() {
	setTimeout(function() {
		// XHR to request a JS and a CSS
		var xhr = new XMLHttpRequest();
		xhr.open('GET', 'http://domain.tld/preload.js');
		xhr.send('');
		xhr = new XMLHttpRequest();
		xhr.open('GET', 'http://domain.tld/preload.css');
		xhr.send('');
		// preload image
		new Image().src = "http://domain.tld/preload.png";
	}, 1000);
};

character encoding utf-8

Which character encoding should I use for my content, and how do I apply it to my content?

Content is composed of a sequence of characters. Characters represent letters of the alphabet, punctuation, etc. But content is stored in a computer as a sequence of bytes, which are numeric values. Sometimes more than one byte is used to represent a single character. Like codes used in espionage, the way that the sequence of bytes is converted to characters depends on what key was used to encode the text. In this context, that key is called a character encoding.

Why use UTF-8?

An HTML page can only be in one encoding. You cannot encode different parts of a document in different encodings.

A Unicode-based encoding such as UTF-8 can support many languages and can accommodate pages and forms in any mixture of those languages. Its use also eliminates the need for server-side logic to individually determine the character encoding for each page served or each incoming form submission. This significantly reduces the complexity of dealing with a multilingual site or application.

There are three different Unicode character encodings: UTF-8, UTF-16 and UTF-32. Of these three, only UTF-8 should be used for Web content. The HTML5 specification says “Authors are encouraged to use UTF-8. Conformance checkers may advise authors against using legacy encodings. Authoring tools should default to using UTF-8 for newly-created documents.”

Real Essence of HTML5

What are those? Any example??

Page load time is one of the most important aspects of the user experience. Unfortunately, troubleshooting a slow page load is not easy because there are many contributing factors. To help with this, We have Navigation timing API.

function onLoad() {
  var now = new Date().getTime();
  var page_load_time = now - performance.timing.navigationStart;
  alert("User-perceived page loading time: " + page_load_time);
}

Establishing “socket” connections between a web browser and a server using Web Sockets API..

High Resolution Time API

The High Resolution Time API provides the current time in sub-millisecond resolution and such that it is not subject to system clock skew or adjustments.

It exposes only one method, that belongs to the window.performance object, called now(). It returns aDOMHighResTimeStamp representing the current time in milliseconds. The timestamp is very accurate, with precision to a thousandth of a millisecond, allowing for accurate tests of the performance of our code.

The most important feature of this method is that performance.now() is monotonically increasing (that is, it increases consistently), so the difference between two calls will never be negative.

A basic example of calling this method is shown below:

1
var time = performance.now();

3. Navigation Timing API

Page load time is one of the most important aspects of the user experience. Unfortunately, troubleshooting a slow page load is not easy because there are many contributing factors. To help with this, in addition to the APIs considered above, the W3C have proposed the Navigation Timing API.

This API offers detailed timing information throughout the page load process accessible through the timingproperty of the window.performance object. In detail, it provides measurements related to page redirects, DNS lookup, time spent building the DOM, TCP connection establishment, and several other metrics.

Network Information API

Another API that deals with performance is the Network Information API. It helps you discover whether the user is on a metered connection, such as pay-as-you-go, and provides an estimate of bandwidth. Thanks to this information, it’s possible to change the behaviour of our pages to accommodate a user in the best way possible. For example, we could conditionally load images, videos, fonts and other resources based on the type of connection detected.

This API belongs to the connection property of the window.navigator object. It exposes two read-only properties: bandwidth and metered. The former is a number representing an estimation of the current bandwidth, while the latter is a Boolean whose value is true if the user’s connection is subject to limitation and bandwidth usage, and false otherwise.

5. Vibration API

Another key concept that gets a lot of attention in our industry is user experience (UX). One of the APIs proposed that allows us to enhance this aspect of our websites is the Vibration API.

This API is designed to address use cases where touch-based feedback is required, and offers the ability to programmatically produce a vibration interacting with the mobile device’s built-in vibration hardware component. If such a component doesn’t exist, it does nothing.

The Vibration API is particularly useful if you’re working with online videos or web games. For example, you could let the user’s device vibrate during the progress of the game in reaction to a particular event.

It exposes only one method, vibrate(), that belongs to the window.navigator object. This method accepts one parameter specifying the duration of the vibration in milliseconds. The parameter can be either an integer or an array of integers. In the second case, it’s interpreted as alternating vibration times and pauses.

A basic use of this API is shown below:

1
2
// Vibrate once for 2 seconds
navigator.vibrate(2000);

6. Battery Status API

The Vibration API isn’t the only one that allows access to a device’s hardware. Another API of this type, designed with mobile devices in mind, is the Battery Status API. It allows you to inspect the state of a device’s battery and fires events about changes in battery level or status.

The Battery Status API exposes four properties (charging, chargingTime, discharingTime, andlevel) and four events. The properties specify if the battery is in charge, the seconds remaining until the battery is fully charged, the seconds remaining until the battery is fully discharged, and the current level of the battery. These properties belongs to the battery property of the window.navigator object.

7. Page Visibility API

The Page Visibility API enables us to determine the current visibility state of the page. What this means is that we’re able to detect if our page is in the background or minimized (i.e. it’s not the currently-focused window).

This capability can help us to develop powerful, yet CPU and bandwidth efficient web applications. In fact, we can slow down or even stop a CPU and/or bandwidth consuming process if we detect the user isn’t using the page.

This API exposes one event, called visibilitychange, that we can listen for to detect changes in the state of the page’s visibility, and two read-only properties, hidden and visibilityState. These properties belong to the document object. hidden is a Boolean whose value is true if the page is not visible, andfalse otherwise. visibilityState is an enumeration that specifies the current state of the document and consists of the following values: hidden, visible, prerender, and unloaded.

8. Fullscreen API

The Fullscreen API provides a way to request fullscreen display from the user, and exit this mode when desired.

This API exposes two methods, requestFullscreen() and exitFullscreen(), allowing us to request an element to become fullscreen and to exit fullscreen.

It also exposes two properties, fullScreenElement and fullScreenEnabled, belonging to the documentobject. These specify the element that has been pushed to fullscreen and if fullscreen mode is currently enabled. It also exposes one event, fullScreenEnabled, which provides us a convenient way to listen for when fullscreen mode has been enabled or disabled.

9. getUserMedia API

The getUserMedia API provides access to multimedia streams (video, audio, or both) from local devices. This means that we can access these streams without the use of Flash or Silverlight. Some use cases for this API include real-time communication and tutorials or lesson recording.

The getUserMedia API exposes just one method called getUserMedia(). It belongs to thewindow.navigator object and accepts as its parameters an object of constraints, a success callback, and a failure callback.

The getUserMedia API also allows us to have a lot of control over the requested stream. For example, we can choose to retrieve a video source at high resolution or at low resolution.

  • Offline apps – This API allows marking pages to be available in Offline mode. This is useful if a resource requires dynamic processing.
  • Indexed database – This API is meant for a database of records holding simple values (including hierarchical objects). Every record has a key and a value. An indexed database is supposed to be implemented using b-trees. Web SQL DB is no longer being pursued as part of HTML5 specification.
  • Web workers – This API is meant to be invoked by web application to spawn background workers to execute scripts which run in parallel to UI page. The concept of web works is similar to worker threads which get spawned for tasks which need to invoked separate from the UI thread.
  • Web storage – This specification defines an API for persistent data storage of key-value pair data in Web clients.
  • Web sockets – This API used for persisting data storage of data in a key-value pair format for Web clients.
    • Server-Sent Events – This API is used for opening an HTTP connection to receive push notifications from a server. These events are received as DOM events. This API is supposed to be used with Push SMS.
    • XMLHttpRequest2 – This API is used to provide scripted client functionality to transfer data between a server and a client.
    • Geolocation – This API is used to provide web applications with scripted access to geographical location information of the hosting device.
    • Canvas 2D Context – This API provides objects, methods and properties to draw and manipulate graphics on a canvas drawing surface.
    • HTML Microdata – This API is used to annotate content with specific machine-readable labels, e.g. to allow generic scripts to provide services that are customized to a page. Microdata allows nested groups of name-value pairs to be added to documents.
    • Media Capture – This API is used to facilitate user access to a device’s media capture mechanism (camera, microphone, file upload control, etc.). This only coves a subset of media capture functionality of the web platform.
    • Web Messaging – This API is used for communications between browsing contexts in HTML documents.
    • Forms – The Forms API can be used with the new data types supported with HTML5.
    • File API – The File APIs are used by the browser to provide secure access to the file system.

Application Cache – A new HTML5 API

A new API among html5 API’s is “Application Cache”.

Just go thru the basics in w3schools or htmlslides prior reading this article.

What is Application Cache?

HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.

Application cache gives an application three advantages:

  1. Offline browsing – users can use the application when they’re offline
  2. Speed – cached resources load faster
  3. Reduced server load – the browser will only download updated/changed resources from the server

To enable application cache, include the manifest attribute in the document’s <html> tag:

<!DOCTYPE HTML>
<html manifest=”demo.appcache”>

</html>

Every page with the manifest attribute specified will be cached when the user visits it. If the manifest attribute is not specified, the page will not be cached (unless the page is specified directly in the manifest file).

The recommended file extension for manifest files is: “.appcache”

The Manifest File

The manifest file is a simple text file, which tells the browser what to cache (and what to never cache).

The manifest file has three sections:

  • CACHE MANIFEST – Files listed under this header will be cached after they are downloaded for the first time
  • NETWORK – Files listed under this header require a connection to the server, and will never be cached
  • FALLBACK – Files listed under this header specifies fallback pages if a page is inaccessible

Once an application is cached, it remains cached until one of the following happens:

  • The user clears the browser’s cache
  • The manifest file is modified (see tip below)
  • The application cache is programmatically updated.

Example:

<html manifest="cache.appcache">
window.applicationCache.addEventListener('updateready', function(e) {
  if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
    window.applicationCache.swapCache();
    if (confirm('A new version of this site is available. Load it?')) {
      window.location.reload();
    }
  }
}, false);

cache.appcache:

CACHE MANIFEST
# version 1.0.0

CACHE:
/html5/src/logic.js
/html5/src/style.css
/html5/src/background.png

NETWORK:
*

Cache status

The window.applicationCache object is your programmatic access the browser’s app cache. Its status property is useful for checking the current state of the cache:

var appCache = window.applicationCache;

switch (appCache.status) {
  case appCache.UNCACHED: // UNCACHED == 0
    return 'UNCACHED';
    break;
  case appCache.IDLE: // IDLE == 1
    return 'IDLE';
    break;
  case appCache.CHECKING: // CHECKING == 2
    return 'CHECKING';
    break;
  case appCache.DOWNLOADING: // DOWNLOADING == 3
    return 'DOWNLOADING';
    break;
  case appCache.UPDATEREADY:  // UPDATEREADY == 4
    return 'UPDATEREADY';
    break;
  case appCache.OBSOLETE: // OBSOLETE == 5
    return 'OBSOLETE';
    break;
  default:
    return 'UKNOWN CACHE STATUS';
    break;
};

Imp points to remember:

A manifest file can have any file extension, but needs to be served with the correct mime-type (see below).

<html manifest="http://www.example.com/example.mf">
  ...
</html>

A manifest file must be served with the mime-type text/cache-manifest. You may need to add a custom file type to your web server or .htaccess configuration.

 

My Example:

HTML File:

<html manifest=”myproj_assets/DemoVIP_country/mf/mobile.mf”>

Script file:

somewhere written..cannot find right now..refer the above code…

Cache file:

CACHE MANIFEST
# 2014-06-16:v50 $Rev: 1050 $ $Date: 2014-06-16:31:56 +0530 (Wed, 16 Jaun 2014) $
# Roulette CB and DT.
# Explicitly cached ‘master entries’ .
CACHE:

# PAGES
../../../myproject/mobilelogin2.htm
../../../myproject/mobilelobby2.htm
# JAVASCRIPT

../../../myproject/scripts/translations/lang_en.js
../../../myproject/scripts/casino.js
../../../myproject/scripts/iscroll4.js
../../../myproject/scripts/jquery-1.9.1.js
../../../myproject/scripts/jquery-ui-1.10.2.js
../../../myproject/scripts/jquery.mobile-1.2.0.js
../../../myproject/scripts/kinetic-v4.7.2.js
../../../myproject/scripts/jquery-migrate-1.2.1.js
../../../myproject/scripts/jquery.fastclick.js
../../../myproject/scripts/jquery.progressbar.js

# STYLES
../styles/merged.min.css
../styles/images/icons-18-black.png
../styles/images/icons-18-white.png
../styles/images/ajax-loader.png

# IMAGES
../images/Logo.png
../images/logo.png
../images/sprites.png

../../common_images/cards/cards.png
../../common_images/ch/player.png

../../common_images/bj/bj_1.png
../../common_images/bj/bj_1_G.png
../../common_images/bj/bj_2.png
../../common_images/bj/bj_2_G.png
# SOUNDS
#images/tick.mp3
NETWORK:

*.txt
*.jsp
*

References: html5rocks

Generic properties used in kinetic js

container String | DomElement Container id or DOM element
x Number <optional>
y Number <optional>
width Number <optional>
height Number <optional>
visible Boolean <optional>
listening Boolean <optional> whether or not the node is listening for events
id String <optional> unique id
name String <optional> non-unique name
opacity Number <optional> determines node opacity. Can be any number between 0 and 1
scale Object <optional> set scale
scaleX Number <optional> set scale x
scaleY Number <optional> set scale y
rotation Number <optional> rotation in degrees
offset Object <optional> offset from center point and rotation point
offsetX Number <optional> set offset x
offsetY Number <optional> set offset y
draggable Boolean <optional> makes the node draggable. When stages are draggable, you can drag and drop the entire stage by dragging any portion of the stage
dragDistance Number <optional>
dragBoundFunc function <optional>
clipFunc function <optional> clipping function
angle Number in degrees
innerRadius Number
outerRadius Number
clockwise Boolean <optional>
fill String <optional> fill color
fillRed Integer <optional> set fill red component
fillGreen Integer <optional> set fill green component
fillBlue Integer <optional> set fill blue component
fillAlpha Integer <optional> set fill alpha component
fillPatternImage Image <optional> fill pattern image
fillPatternX Number <optional>
fillPatternY Number <optional>
fillPatternOffset Object <optional> object with x and y component
fillPatternOffsetX Number <optional>
fillPatternOffsetY Number <optional>
fillPatternScale Object <optional> object with x and y component
fillPatternScaleX Number <optional>
fillPatternScaleY Number <optional>
fillPatternRotation Number <optional>
fillPatternRepeat String <optional> can be “repeat”, “repeat-x”, “repeat-y”, or “no-repeat”. The default is “no-repeat”
fillLinearGradientStartPoint Object <optional> object with x and y component
fillLinearGradientStartPointX Number <optional>
fillLinearGradientStartPointY Number <optional>
fillLinearGradientEndPoint Object <optional> object with x and y component
fillLinearGradientEndPointX Number <optional>
fillLinearGradientEndPointY Number <optional>
fillLinearGradientColorStops Array <optional> array of color stops
fillRadialGradientStartPoint Object <optional> object with x and y component
fillRadialGradientStartPointX Number <optional>
fillRadialGradientStartPointY Number <optional>
fillRadialGradientEndPoint Object <optional> object with x and y component
fillRadialGradientEndPointX Number <optional>
fillRadialGradientEndPointY Number <optional>
fillRadialGradientStartRadius Number <optional>
fillRadialGradientEndRadius Number <optional>
fillRadialGradientColorStops Array <optional> array of color stops
fillEnabled Boolean <optional> flag which enables or disables the fill. The default value is true
fillPriority String <optional> can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority(‘color’) to render the shape with a color fill, or use setFillPriority(‘pattern’) to render the shape with the pattern fill configuration
stroke String <optional> stroke color
strokeRed Integer <optional> set stroke red component
strokeGreen Integer <optional> set stroke green component
strokeBlue Integer <optional> set stroke blue component
strokeAlpha Integer <optional> set stroke alpha component
strokeWidth Number <optional> stroke width
strokeScaleEnabled Boolean <optional> flag which enables or disables stroke scale. The default is true
strokeEnabled Boolean <optional> flag which enables or disables the stroke. The default value is true
lineJoin String <optional> can be miter, round, or bevel. The default is miter
lineCap String <optional> can be butt, round, or sqare. The default is butt
shadowColor String <optional>
shadowRed Integer <optional> set shadow color red component
shadowGreen Integer <optional> set shadow color green component
shadowBlue Integer <optional> set shadow color blue component
shadowAlpha Integer <optional> set shadow color alpha component
shadowBlur Number <optional>
shadowOffset Object <optional> object with x and y component
shadowOffsetX Number <optional>
shadowOffsetY Number <optional>
shadowOpacity Number <optional> shadow opacity. Can be any real number between 0 and 1
shadowEnabled Boolean <optional> flag which enables or disables the shadow. The default value is true
dash Array <optional>
dashEnabled Boolean <optional> flag which enables or disables the dashArray. The default value is true

 

Kinetic Js Introduction

KineticJS is an HTML5 Canvas JavaScript framework that enables high performance animations, transitions, node nesting, layering, filtering, caching, event handling for desktop and mobile applications, and much more.

In order to understand what KineticJS is, you must be familiar with JavaScript development and should know the basics of HTML5 Canvas programming. KineticJS is a JavaScript library that helps us simplify the development of interactive HTML5 applications. In this case interactive applications are different 2D applications such as games, image editors, interactive maps, cartoons, and more (just turn on your imagination). From a technical point of view it is an extension to the HTML5 Canvas 2D context in the form of a JavaScript library. In addition, your application will work on all browsers that support HTML5, and even on mobile devices.

With KineticJS you can draw shapes on the stage and manipulate them using the following elements:

  • Move
  • Rotate
  • Animate

Of course, you can implement all the necessary HTML5 Canvas functionality without KineticJS, but you have to spend a lot more time, and not necessarily get the same level of performance. The creators of KineticJS put all their love and faith into a brighter future of HTML5 interactivity. The main advantage of the library is high performance, which is achieved by creating two canvas renderers – a scene renderer and a hit graph renderer. One renderer is what you see, and the second is a special hidden canvas that’s used for high-performance event detection. A huge advantage of KineticJS is that it is an extension to HTML5 Canvas, and thus is perfectly suited for developing applications for mobile platforms. It is a known fact that the iOS platform does not support Adobe Flash. In this case, KineticJS is a good Flash alternative for iOS devices.

In short, the following are the main advantages of KineticJS:

  • Speed
  • Scalability
  • Extensibility
  • Flexibility
  • Familiarity with API (for developers with the knowledge of HTML, CSS, JS, and jQuery)

All is well for now :D. But how to start with?? No worries..browse to kineticjs and click download on homescreen, where it will redirect to a page having js code..copy it and paste it in a notepad file and save as kinetic.js.

Now just use the script like all other external scripts..,

Example: Lets consider to draw a rectangle using kinetic js…

1. Include the kinetic javascript file in your html page..

2. create a container with div tag

3. declare stage and specify your container name,width and height. I knew, like me you have striked with one doubt..what is stage and why it is used? right? Ans is here…A stage is a place where you can create layers( Layers are tied to their own canvas element and are used to contain groups or shapes  ) and draw your shapes. In my understanding, i consider it as a paper on pad.

4. Next layer is declared. If at all required you can add up attributes/properties you need.

5. Now create a rectangle with your own dimensions.

6. Finally add this rectangle to layer and layer to stage which is resided in a div tag.

7.  Run the code

Screenshots:

1. Code

24-06-2014 17-17-56

2. Output

24-06-2014 17-29-16

 

For more:

http://kineticjs.com/docs

http://www.html5canvastutorials.com/kineticjs/

Canvas Transform

Folks,

This is one of the significant concept in canvas. Lets dive in deeper to understand it clearly.

Before we start up with this, first you should know what is shear matrix, translation matrix(explained with translation matrix).

Representation of shear can be found here

Representation of translation can be found here

Lets know what is scaling in canvas too

Lets begin the transform show 😉

Each object on the canvas has a current transformation matrix.

The transform() method replaces the current transformation matrix. It multiplies the current transformation matrix with the matrix described by:

a c e
b d f
0 0 1

Shear and translation matrix representation

a sx tx
sy d ty
0 0 1

In other words, the transform() method lets you scale, rotate, move, and skew the current context.

Note: The transformation will only affect drawings made after the transform() method is called.

Note: The transform() method behaves relatively to other transformations made by rotate(), scale(), translate(), or transform(). Example: If you already have set your drawing to scale by two, and the transform() method scales your drawings by two, your drawings will now scale by four.

JavaScript syntax: context.transform(a,b,c,d,e,f);

 

a Scales the drawing horizontally Play it »
b Skew the the drawing horizontally Play it »
c Skew the the drawing vertically Play it »
d Scales the drawing vertically Play it »
e Moves the the drawing horizontally Play it »
f Moves the the drawing vertically Play it »

 

Now its very simple,

You can some requirement to skew up/down (or) shear matrix?? – context.transform(a, sy, sx, d, e, f);

You can some requirement to translate x/y coordinates (or) translate matrix?? – context.transform(a, b, c, d, tx,ty);

You can some requirement to Scale Up/down ?? – context.transform(scale-x, b, c, scale-y, e,f);

Now in total i represent entire transform syntax like this..

transform(scale-x, sy, sx, scale-y, tx,ty);

I hope its very clear now in way of using transform with your requirement :D. Good luck

You can refer below sites too:

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations

http://www.html5canvastutorials.com/

http://www.w3schools.com/