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

Thursday, December 4, 2014

Lazy Loading of Images With JavaScript and JQuery (a Plugin)

Intro

Have you noticed a growing number of websites that load images while you are scrolling down the page? Even if you haven't, just pretend that you have, or hey read on anyways! I'll try to entertain you. These pages are using a technique called lazy loading for the images. Your browser does not download the image until the image is at or near the viewport (not downloaded until you the client need to see the image), thus potentially saving on bandwidth and initial page display time for the user. Under the assumption that most visitors won't view every image in a large scrollable list, this can be quite a boon for you (the host) and for your users (the clients). If you're intrigued and want to read about one way to accomplish this feat, read on!

How to use the plug-in

There are quite a number of ways to lazy load images, but for this article I'll focus on just one. A JQuery plugin named unveil by Luis Almeida. For those of you unfamiliar with JQuery, I suggest you read up about it on their website before continuing. It will help you to have a basic understanding of what it does and how it works. If you want just the cliff-notes version, it's a lightweight (small download size) JavaScript library that handles a multitude of tedious tasks for you, and it has a very vibrant ecosystem of plugins from thousands of contributors.

Back to unveil...this plugin lets you specify a placeholder image for images as well as the final lazy-loaded ultimate image that the user will see. It's got just a couple other configuration options, but you can read about those on the unveil site linked below. We'll use it in it's most basic capacity, downloading an image lazily when the user scrolls down to that portion of the page. So, let's see how to use it.

Fire up your favorite html editor and create yourself an html page. Paste the content you see below into your html file:

<!DOCTYPE html>
<html>
 <head>
  <!-- link to jquery library hosted by google -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <!-- link to unveil library in the same directory as this html file -->
  <script src="jquery.unveil.js"></script>
 </head>
 <body>
  <div style="height: 1000px;">
   hi!
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://digitalis.nwp.org/sites/default/files/stuff_1.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://static.tumblr.com/429df189c9e81bb388196fb442db77ba/vbdvuoy/xrUmksw6n/tumblr_static_green-stuff.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://images.electricpig.co.uk/wp-content/uploads/2012/01/internet-stuff.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcT3WjcjnXnXG3MIZZ1rw3dQsjrx-06ogqZbcjArDwM3n1Q9ixrwCw" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://www.abc.net.au/tv/stuff/stuff_wendy.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ-5Ud4e36C7a9xsXgKr6ETuuecqSNorBhiWWelWj4UyfIUzzUwHg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://tosaenglish.com/wp-content/uploads/2012/06/image.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://www.seren.bangor.ac.uk/wp-content/uploads/2012/10/story-of-stuff-book-adds-to-the-vision-of-decreased-consumption.jpeg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://i.imgur.com/c6D2qCb.jpg" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="http://sd.keepcalm-o-matic.co.uk/i/keep-calm-and-stop-saving-stuff-on-desktop.png" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSvKoJ_CqT0yZQFelslk6DUralqV73_SfzuiTa30e6YC1cLzkxY" />
  </div>
  <div>
   <img src="http://www.clker.com/cliparts/v/W/8/R/B/w/blue-circle-th.png" 
    data-src="https://lh4.googleusercontent.com/-ZknF9DJA52o/AAAAAAAAAAI/AAAAAAAAAB4/JKBNFb96bM0/photo.jpg" />
  </div>
  <script>
   $(document).ready(function() {
     $("img").unveil(-400);
   });
  </script>
 </body>
</html>

Let's go over this code in sections. The first section I want to talk about is the "<head>" section of the html file. The important bits are the 2 script links. The first one links to a version of JQuery hosted by google servers. The 2nd script links to a js file that is expected to exist in the same location as your html file. Save the unveil js file to your hard drive in the same place where you have the html file.

The next part to talk about is all them thar div tags. The first one makes sure we have 1000 pixels taken up by useless stuff. I did this so that you could better play with the scrolling effect of lazy loaded images. The remaining divs are all containers for img tags. For those of you used to using img tags already, you know what the src attribute is; it's the url of the image to display. In the case of the above img tags, we're linking to a single placeholder image file which is a blue circle. Each of these img tags also contains a special data-src attribute which in the case of the unveil JQuery plugin, contains the image that will be downloaded and displayed when the user's viewport scrolls the image into view. Long story short, this is the image you'll actually see.

The last chunk of code I want to discuss is the final script tag. This contains our jquery function (the document.ready) which fires off when the document has finished loading. Our function above will apply the unveil plugin to any img tag on the page. The -400 in there tells unveil to only "unveil" the real image after it's 400 or more pixels into the viewport. If you specify no value here at all the image is unveiled precisely when it gets into the viewport, and this is normally what you'll want, but for this sample I wanted you to see the placeholder images a little better.

OK go ahead and open up the html file in your favorite browser! Depending on your monitor resolution, you might either see just the word "hi!", or maybe you'll see a blue circle or 2 at the bottom of your screen. Now scroll down slowly. You'll see the blue circles come up on screen, and if you keep scrolling they turn into other images (the final destination images as denoted by data-src). Pretty nifty huh? Feel free to play around with that -400, change it to other values to see the change in behavior. The closer you get to 0, the less time (vertical scroll-wise) you'll have to see the blue placeholder circles. The more negative the number gets, the longer you see the blue placeholders.

If you get truly excited by all this, you can bring up the developer tools of your favorite browser (mostly by hitting the F12 key) and watching the timing of image downloads to confirm you're getting what you think you're seeing.



What's Next?

There are other lazy loading JS image libraries out there, including some that are JQuery plugins. Play around with them and see if you find another you like. I like this one because it's extremely light-weight and easy to use, but maybe you'll find one you like better.

You could also create your own sample page from scratch. That's the best way to learn after all, not by copying something another person has already done.

Resources

unveil
JQuery

Thursday, October 16, 2014

SignalR and WebSockets

Intro

WebSocket is a new protocol, developed alongside HTML5, that allows a 2-way communication between client and server. With HTTP and your standard web browsers the communication is all 1-way; the client requests resources from the server and the server serves them. With WebSockets the server can send messages to the client without the client first requesting those resources. Messages can be passed from client to server and from server to client, keeping the socket connection open. Not all the grass is green in this land of Eden though; because this is a newer technology, not all browsers support WebSockets just yet.

This is where SignalR comes in. SignalR is an ASP.Net library that simplifies 2-way communication between the server and the client. It's an implemention of WebSockets, but it's not just that. It will use WebSockets when both the server and client support it, but when one or both does not support WebSockets it will fall back to other technologies that accomplish the same goal in similar ways. Simply put, SignalR allows you to use 2-way communication between client and server using whatever is the best way you are capable of using. Plus, the fallback mechanism happens behind the scenes. This means that you the coder code a single codebase for communication and SignalR makes the choice of which method to use for you. And, one extra bit of info...SignalR allows you to call client-side JavaScript functions from the server. That's some cool stuff!

To the Code!

Create yourself a new Asp.Net web application. Mine's named BlogSignalR1.


Make it an Empty web app with no folders, no core references, and no authentication.

Now add the NuGet package named SignalR.



Now add a class to your project named NotificationHub. Our app will have a single page where we, on the server, can notify our users of things that are about to happen on the website in real-time. This new class is what we'll use on the server-side to send those messages.

Here is the content you'll want for your new class:

using Microsoft.AspNet.SignalR;

namespace BlogSignalR1
{
    public class NotificationHub : Hub
    {
        public void Send(string message)
        {
            Clients.All.broadcastMessage(message);
        }
    }
}


Go ahead and create another new class in your website named Startup. This class will tell Asp.Net to fire up/initialize SignalR. Here's the code for it:

using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(BlogSignalR1.Startup))]
namespace BlogSignalR1
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}


Now it's time to work in client-side code a little. First create a new html page in the project. Name the file default.html. Here's the content of that one:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Basic User Page</title>
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
</head>
<body>
    Hi user!
    <div id="notificationArea">

    </div>
    <!--Script references. -->
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var notification = $.connection.notificationHub;
            // Create a function that the hub can call to broadcast messages.
            notification.client.broadcastMessage = function (message) {
                // Html encode display name and message.
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#notificationArea').text(encodedMsg);
            };

            //create a connection to the hub
            $.connection.hub.start().done(function () {
                //sometimes you might need to do something after creating the connection to your hub; for this example, we do not
                });
        });
    </script>
</body>
</html>


This is a very simple page whose sole purpose is to display notifications from a site admin within the div named notificationArea.

Note: there is a possibility your version of either SignalR or JQuery may be different than mine. If so, please modify the script references as necessary to reflect the version you have in your Scripts folder.

The above html file implies we need one more file, this one for admins to create notifications for users. Go ahead and create a new html file called admin.html. Here's the content:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Basic Admin Page</title>
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
</head>
<body>
    Hi Admin!
    <label for="message">Message:</label><input type="text" id="message" />
    <button id="disseminate">Disseminate</button>

    <!--Script references. -->
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var notification = $.connection.notificationHub;
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#disseminate').click(function () {
                    // Call the Send method on the hub.
                    notification.server.send($('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>



Another simple page; one entry where you enter text, one button that you click to get it to push out a notification to clients. Let's try it out!

Go ahead and run the solution, navigate to default.html. Open up a 2nd tab in your browser and navigate to admin.html. Type some text into the entry on the admin page and click the Disseminate button.


Now go back over to the other tab containing default.html and your text is there!

Yes that's right folks, with a little bit of server-side code and a little bit of client-side code, you can create a basic site that allows real-time 2-way communication using SignalR. This is some wonderful technology that has tons of potential uses (chat is the most oft-talked-about usage for SignalR and WebSocket technology). If you want to make sure I'm not fooling you, just drop a breakpoint in your server-side and client-side methods and you'll see the trip from admin.html client, to server-side NotificationHub class, back down to default.html. It's mesmerizing!

What's Next?

Play around with the code and see if you can figure out what all of that JavaScript is doing. I find the best way to dig through stuff is to set breakpoints and trace into it and I'm sure you'll have luck with that method too. You can also dig around in the SignalR documentation and tutorials, as I've provided a link to such beasts down in the Resources section.

Resources

SignalR
WebSocket
My Code

Wednesday, August 27, 2014

jquery advanced: roll your own plugin

PREFACE:

So we've hidden some text, changed the size/color of other text at the click of a button, and made a pictorial slideshow.  Now what?  Our second adventure in jquery required the usage of some extra plugins, this adventure we'll learn how to write our own jquery plugins to use!

CODING CONCEPT:

Let's go for some more cheese:  reversing the text of list items we have displayed to the user.  It being football season, let's pick on four different teams from the NFL!

ACTUAL CODE:


The plugin code! Please note I've named the file jquery.reverseme.js

The html code used to call the .js file above:

Our final end product when rendered in a browser:


SOURCE:

http://www.sitepoint.com/how-to-develop-a-jquery-plugin/