How to “Really” defer loading of JavaScript?

The websites nowadays uses a LOT of JavaScript. However, defer loading of JavaScript is actually a big headache as there’s really, really many ways to do it. Someone may call you “just use defer” or “just use async” or even “just put it on the bottom of the page”.

Actually, none of these methods really solve the problem that allows a page to be fully loaded before loading scripts. None of these methods actually gets passed of the “Defer loading of scripts” if you’re trying to test it with Google PageSpeed.

The right way

In here, I’ll show you the right method of defer loading JavaScript that Google also recommends.

Beware: You should put this just before </body> (near the end of an HTML file)

<script type="text/javascript">
function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js"; // replace defer.js with your script instead

if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;

What it really does is to load the JavaScript after the page has been fully load i.e. The onload event has been triggered.

Why the other methods don’t work?

The methods of inlining, placing scripts at the bottom, using “defer” or using “async” all do not accomplish the goal of letting the page load first then loading JS and they certainly do not work universally and cross browser.



You can see that with this method, the page load speed has a very great increase. As the other methods don’t match the goal of loading JavaScript only after the page has finished loading, it can be very slow especially for large JS files.

Final word

Our first priority is to deliver the content to the user as soon as possible. If a user waits because there’s some JavaScripts still loading that doesn’t affect the content, the user may leave because of the long waiting. (The average wait time for a visitor is around 2 – 3 seconds) Therefore, you should remember the right method of deferring JavaScript loading.

Human friendly time parses with tidytime.js

Have you ever feel bored with standard time format like 08:30? Do you want time strings that looks great? Now you can do it with tidytime.js. Tidytime.js is a jQuery plugin that transforms standard time notation to something that’s human-friendly.


As you can see, it can transform standard time notation into human-friendly parses. Isn’t it great? Let’s see how to use this great plugin.

First, you need to include jQuery & tidytime.js.

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="tidyTime.js"></script>

After that, create an element that holds the time.

<span class="tidytime"></span>

The easiest way to use tidytime.js is to call it with no options.

$(document).ready(function ($) {

If you want to call it with options, you can do it like this:

    time: '08:15', //The time string in hh:mm format
    before: 'It\'s ', //The string appended before tidytime string
    after: ' and I\'m feeling good!', //The string appended before tidytime string
    periodOfDay: true, //Show parses like 'in the morning', 'in the afternoon', 'in the evening' and 'at night'
    callback: tidyTimeFunction //The name of the function that you would like pass as a callback once the time has been updated

Additional details can be found at

Audio visualizations using Web Audio API

Have you ever seen some visual effects when playing music with your favourite music player? (Here’s some example photos.)




This is just… great. But how they do this kind of effects? We need to understand how sound is made first. Sound is actually the vibrations of air (and more generally, objects) and the change in air pressure is recorded using a microphone. Everytime when you play a music, the speakers generates the vibrations using the change in air pressures recorded by microphone.

We can make use of these data to make visual effects from sounds. In this tutorial, I’ll teach you how to create a visualization like this:


In this demonstration, we’ll be able to drop audio files in and play the music with visuals. OK! Let’s start!

First, we need to set up the HTML for our visuals. It’ll be pretty simple as we only need a canvas.

<canvas id="canvas" style="width: 100%; height: 100%;"></canvas>

Then, it’s time to code some JavaScript!

// Init. all the variables we need
var audio, source, analyser, canvas, ctx;

// Logs messages
function clog(str) {
    if (window.console && console.log) console.log(str);

// This is an empty event handler
// thatprevents the event from happening
function noop(e) {

// This is the function used to
// handle the drop of the audio files.
function drop(e) {
    // Prevents the default action of the event
    // In this case, open an audio file

    // Creates a file reader
    var reader = new FileReader();

    // What should we do when the reader is ready?
    reader.onload = function(e) {
        // Decode the audio file
        // using the Web Audio API
        if (audio.decodeAudioData) {
            audio.decodeAudioData(, function(b) {
                source.buffer = b;

                // Play the audio file
            }, function(e) {
                alert('Audio not playable or not supported.');
        else {
            source.buffer = audio.createBuffer(, true);

            // Play the audio file

    // Read the dropped file

// The function that actually
// draws the visuals
function draw(e) {
    // Get the audio data
    var inp = e.inputBuffer.getChannelData(0);
    var out = e.outputBuffer.getChannelData(0);

    // Start drawing the visuals
    // We first clear the canvas first
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.strokeStyle = '#6633FF';
    ctx.moveTo(0, canvas.height / 2);

    // Loop through the data and plot them
    for (var i = 0; i < inp.length; i++) {
        out[i] = 0;
        i == 0 ? ctx.moveTo(0, canvas.height / 2 + inp[i] * canvas.height / 2) : ctx.lineTo(canvas.width * i / inp.length, canvas.height / 2 + inp[i] * canvas.height / 2);

    // Draw it!

window.onload = function() {
    // Init. the audio context
    // and the canvas
    audio = new(window.AudioContext || window.webkitAudioContext)();
    canvas = document.querySelector('#canvas');
    ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // Listen for file drop
    // We also need to prevent the default actions of
    // other related events
    canvas.addEventListener('dragover', noop, false);
    canvas.addEventListener('drop', drop, false);
    document.addEventListener('dragover', noop, false);
    document.addEventListener('drop', drop, false);

    // Create the audio source
    // and the analyser that
    // actually gets the audio data
    source = audio.createBufferSource();
    analyser = audio.createScriptProcessor(1024, 1, 1);
    analyser.onaudioprocess = draw;
    source.loop = true;
    source.gain.value = 1;

// Handle window resize
function resize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

// Add the resize listener
window.addEventListener('resize', resize, false);

OK, it’s finished. I’ve prepared a live demo for all you guys. Enjoy! 🙂

Create real-time updates using Server-sent Events and libSSE

When I first learn node.js, I learned how to use, a node.js module for real-time communication between the client and server. However, when I’m going back coding PHP for a while, I started to figure out only few PHP libraries offered this functions and the techniques they uses are old (AJAX Streaming, Forever <iframe>, etc.). One day I found a new technique called Server-sent Events and it’s pretty easy to implant. I have an idea of creating an interface for Server-sent Events in order to speed up development and make it easier to use. libSSE is the library I’ve create just for this and it’s event-based which means data is sent only when an event happens. It also has some utility classes for communicate with other PHP scripts.

Here’s the library:

It’s pretty easy to use. Here’s an example.

require_once('./src/libsse.php');//include the library

//create the event handler
//every event must inherit the base event class SSEEvent
class YourEventHandler extends SSEEvent {
    public function update(){
        //Here's the place to send data
        return time();
    public function check(){
        //Here's the place to check when the data needs update
        return time() % 20 === 0;

$sse = new SSE();//create a libSSE instance
//register your event handler
    'event_name', //The name of the event
    new YourEventHandler() //The event handler defined above
$sse->start();//start the event loop

On the client-side you need to set up an EventSource object to listen event from server.

var sse = new EventSource('path/to/your/sse/script.php');
    var data =;
    //handle your data here

Remember that Server-sent Events is still a new standard and not all browsers supports it. However, polyfills are available for them. Hope you like it and find it useful.

Draw fireworks in HTML5 canvas (with sounds!)

I always wondered if we can make cool fireworks animation using a procedural way (in here it simply means not using any image sprites or other things like that). Finally, I successfully learned that from this tutorial and I think it missed something: how can a great graphics like this without sounds? So I added it and show it to you. Hope you can also learned something like me.