HTML5 and CSS3, Second Edition

(singke) #1
We can download a copy of the web-socket-js library^8 and place it within our
project. We’ll use Modernizr again to detect for support and load in the
JavaScript files on our page. First, we add Modernizr to our page, using the
customized version that includes the load() function like we used in Detecting
Features with Modernizr, on page 47:

html5_websockets/index.html
<scriptsrc='javascripts/modernizr.js'></script>

Then in javascripts/chat.js we use Modernizr.load() to load and configure the fallback:


html5_websockets/javascripts/chat.js
➤ Modernizr.load(
➤ {
➤ test:Modernizr.websockets,
➤ nope:
➤ {
➤ "swfobject":"web-socket-js/swfobject.js",
➤ "websocket":"web-socket-js/web_socket.js"
➤ },
➤ callback:function(url,result,key){
➤ if(!result){
➤ if(key==="swfobject"){
➤ WEB_SOCKET_SWF_LOCATION="web-socket-js/WebSocketMain.swf";
➤ WEB_SOCKET_DEBUG= true;
➤ }
➤ }
➤ },
➤ complete:function(){
setupChat();
➤ }
➤ }
➤ );

When our browser doesn’t support sockets, the library gets loaded, but we
also need to set a variable that specifies the location of the WebSocketMain file,
so we do that in the callback(), but only when socket support isn’t available.

We’re loading two separate scripts here, and the callback() gets fired once for
each script that gets loaded. Modernizr lets us tag each script with a key. It
passes the key to the callback. This way we can tell which script was loaded.
In this example we’re using the key to identify when the web-socket script
was loaded so we can set the variables the fallback requires.

Regardless of whether the browser supports sockets, we always have to run
the setupChat() method so the chat application starts. To do that, we move the


  1. https://github.com/gimite/web-socket-js/archive/master.zip


Chapter 10. Creating Interactive Web Applications • 224


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf