Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Sunday, March 23, 2014

When scripts should run?

A quick walkthrough on when executing a script in the browser.

A lot of examples on the internet show to wrap the code inside the jQuery "ready" event handler. It is not always the case. As a matter of fact you can execute a script in three different fashions:
  • immediately
  • in the ready event handler
  • in the load event handler
  • under another event handler (but this is a different story though)

Immediately

You can execute a script immediately if your script doesn't rely on the DOM, or rely on a fragment of DOM that is already been loaded (because is placed before your script).
I think this is often the preferred case.

JQuery ready

The jQuery ready event handler uses the  domcontentloaded event but is guaranteed to be executed right away if this event is already been fired.
"The handler passed to .ready() is guaranteed to be executed after the DOM is ready"
You should execute your script here if it runs before the fragment of DOM targeted by the script. Given this, if you are loading synchronously you should definitely put the script at the bottom of the HTML and just execute it immediately.

On load

There are rare cases when you need the CSS and images loaded before executing the script. A suggestion: avoid it if you can! For example you could (and definitely should) add the width and height attribute on any img and you can use a bit of inline css styling (in some edge case).
In the few cases you really need this you can use the load event handler.

Asynchronous loading

If you use requirejs you really don't have a clue on when your script is executed. Luckily enough executing it immediately or inside a jQuery ready event is always safe. It's not so using the load event.
Your script could be loaded after the load event is already been fired. For this reason is a good idea to check it and, in case, executing the script immediately.

function mycode(){
   ...
}

if (document.readyState == "complete"){
    mycode();
}
else {
    $(document).load(mycode);
}

Ajax fragments

When you load or create a new fragment of html sometimes you need to run the some code against the new fragment. This can be avoided the vast majority of time using event delegation adding your event handlers to a wrapper node (or to the document itself). If you really need to manage this I suggest to generate a custom event to manage these cases. For example:

// loading a fragment
var $result = $("#result")
$result.load("ajax/test.html", function (){
    ...
    $result.trigger('nodeloaded');
    ...
});

...
// trigger on the document ready 
// for the whole document
$(document).ready(function (evt){
    $(document).trigger('nodeloaded');    
});

...

// manage the event
$(document).on("nodeloaded", function (evt){
    $('.your-class', evt.target).yourplugin();
});

You can find something similar used in jquery mobile.


Monday, December 12, 2011

Adaptative web design: loading resources dinamically

Adaptative web design (also known as responsive web design) is a tecnique that adapts web pages to the devices (desktops, tablets and phones).

This tecnique uses many differents technologies. In this blog post I don't want to explain every detail of this tecnique but it could be useful reading an in-depth tutorial:
http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

The remaining Issue
Using media queries to adapts a web page to mobile has a huge drawback.  We load to a mobile phone every bit of the web page and then we hide text and shrink full size images and video. The results is great, but the speed ? Is it possible to avoid downloading all this unused stuff ?

I think I found an elegant solution with these scripts https://github.com/sithmel/jQuery-decomment .
They are very simple (only 31 LOC) and are designed to work together. They are doWhenVisible and decomment.

An example:
Our Web page contains a very big and complex slideshow but in the mobile version of our web site we'll hide it using css (is very big and heavy to load).

HTML

<div class="bigslideshow">
<!--
    <img src="bigimage1.jpg" />
    <img src="bigimage2.jpg" />
    <img src="bigimage3.jpg" />
-->
</div>

CSS

@media screen and (max-width: 650px) {
    .bigslideshow{
       display: none;
    }
}

Javascript

$.doWhenVisible('.bigslideshow', function (){
    this.decomment(); // remove the comments
    this.jcarousel(); // initialize the slideshow
});

Very easy ! doWhenVisible execute a callback (only once) when a DOM element becomes visible (it checks every time the page is resized).
Decomment obviously removes comments. Removing comments is just like adding dinamically DOM nodes. The browser reacts downloading the resources and rendering the whole.

We can go even further using a script loader to load our js only if effectively used (we use require.js here):

$.doWhenVisible('.bigslideshow', function (){
    require(["jquery.jcarousel.js"], function() {
    //load jcarousel
        this.decomment(); // remove the comments
        this.jcarousel(); // initialize the slideshow
    });
});
Right now I'm very proud of these little scripts!

Tuesday, October 11, 2011

How to write a good Javascript widget


Writing a Javascript widget is almost easy but I learnt at my expense that it may be tricky. So I wrote some simple rule that help to do the job well.

1 - keep in mind: progressive ehnancement
I already wrote about it, just a recap: write html semantically correct (your mark up MUST have sense even WITHOUT Javascript)
2 - do not use inline styling (use CSS)
When your script are about to create your widget, find the outermost element and give to it a specifical class. Then do not attach style directly to the DOM elements, instead use CSS.
In this way you can customize the style of your widget without touching a single line of Javascript.
3 - avoid FOUC
Usually you modify the DOM after it is loaded. That way you may see the page while change. This is called FOUC (flash of unstyled content). You can avoid this hiding the DOM nodes you are about to change (using CSS) and show after (using Javascript).
Just a suggestion: you can use a noscript tag to show what you have hidden before in case Javascript is not enabled.
4 - use a library
A library like jQuery helps a lot with the DOM manipulation, It helps to forget the differences between the browsers. You can find a thorough guide to make a plugin here.
5 - do not calculate size and position during the widget creation
You can't assume what part of your page will be displayed and when. So you can't calculate position and size of elements at creation time. An example: I used this spinner widget on my application (http://btburnett.com/spinner/example/example.html). The widget calculates the input dimension and adds a lot of on-line styling for the little arrows. But in my application display the widget inside an hidden tab and all the size calculation returns wrong results.