Friday, February 14, 2014

Multiple Simultaneous Ajax Requests (with one callback) in jQuery

A post by Chris Coyier @ http://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/

Multiple Simultaneous Ajax Requests (with one callback) in jQuery

PUBLISHED BY CHRIS COYIER
Let's say there is a feature on your website that only gets used 5% of the time. That feature requires some HTML, CSS, and JavaScript to work. So you decide that instead of having that HTML, CSS, and JavaScript on the page directly, you're going to Ajax that stuff in when the feature is about to be used.
We'll need to make three Ajax requests. Since we don't want to show anything to the user until the feature is ready to go (plus they all kinda rely on each other to work right) we need to wait for all three of them to be complete before proceeding.
What's the best way to do that?
Ajax calls in jQuery provide callbacks:
$.ajax({
  statusCode: {
    url: "/feature",
    success: function() {
      // Ajax success
    }
  }
});
Or the "Deferred" way, this time using a shorthand $.get() method:
$.get("/feature/").done(function() {
  // Ajax success
});
But we have three Ajax requests we're needing to perform, and we want to wait for all three of them to finish before doing anything, so it could get pretty gnarly in callback land:
// Get the HTML
$.get("/feature/", function(html) {

  // Get the CSS
  $.get("/assets/feature.css", function(css) {
    
    // Get the JavaScript
    $.getScript("/assets/feature.js", function() {

       // All is ready now, so...

       // Add CSS to page
       $("<style />").html(css).appendTo("head");

       // Add HTML to page
       $("body").append(html);

    });

  });

});
This successfully waits until everything is ready before adding anything to the page. So by the time the user sees anything, it's good to go. Perhaps that makes some of you feel nauseated, but I've done things that way before. At least it makes sense and works. The problem? It's slow.
One request ... wait to be done ... another request ... wait to be done ... another request ... wait to be done ... go.
It would be faster if we could do:
All three requests in parallel ... wait for all three to be done ... go.
We can use a bit of Deferred / Promises action to help here. I'm sure this is some JavaScript 101 stuff to some of you but this kind of thing eluded me for a long time and more complex Promises stuff still does.
In our simple use case, we can use jQuery's $.when() method, which takes a list of these "Deferred" objects (All jQuery Ajax methods return Deferred objects) and then provides a single callback.
$.when(

  // Deferred object (probably Ajax request),

  // Deferred object (probably Ajax request),

  // Deferred object (probably Ajax request)

}.then(function() {

  // All have been resolved (or rejected), do your thing

});
So our callback-hell can be rewritten like:
$.when(
  // Get the HTML
  $.get("/feature/", function(html) {
    globalStore.html = html;
  }),

  // Get the CSS
  $.get("/assets/feature.css", function(css) {
    globalStore.css = css;
  }),

  // Get the JS
  $.getScript("/assets/feature.js")

).then(function() {

  // All is ready now, so...

  // Add CSS to page
  $("<style />").html(globalStore.css).appendTo("head");

  // Add HTML to page
  $("body").append(globalStore.html);

});

Another use case: mustard cutting

My use-case example above is a 5% feature. Keep the page lighter for the 95% of users who don't use the feature, and have it be a relatively quick add-on for those that do.
Another situation might be a cut-the-mustard situation where you add in additional features or content to a page in certain situations, as you decide. Perhaps do amatchMedia test on some media queries and determine the device's screen and capabilities are such that you're going to include some extra modules. Cool, do it up with some parallel Ajax calls!

Thursday, February 6, 2014

Database Schema for Tagging System


Tags: Database schemas
Recently, on del.icio.us mailinglist, I asked the question “Does anyone know the database schema of del.icio.us?”. I got a few private responses so I wanted to share the knowledge with the world.

The Problem: You want to have a database schema where you can tag a bookmark (or a blog post or whatever) with as many tags as you want. Later then, you want to run queries to constrain the bookmarks to aunion or intersection of tags. You also want to exclude (say: minus) some tags from the search result.
Apparently there are three different solutions (Attention: If you are building a websites that allows users to tag, be sure to have a look at my performance tests as performance seems to be a problem on larger scaled sites.)

"MySQLicious" solution


mysqlicious sample datamysqlicious database stucture
In this solution, the schema has got just one table, it is denormalized.
I named this solution “MySQLicious solution” because MySQLiciousimports del.icio.us data into a table with this structure.

Intersection (AND)

Query for “search+webservice+semweb”:
SELECT *
FROM `delicious`
WHERE tags LIKE "%search%"
AND tags LIKE "%webservice%"
AND tags LIKE "%semweb%"

Union (OR)

Query for “search|webservice|semweb”:
SELECT *
FROM `delicious`
WHERE tags LIKE "%search%"
OR tags LIKE "%webservice%"
OR tags LIKE "%semweb%"

Minus

Query for “search+webservice-semweb”
SELECT *
FROM `delicious`
WHERE tags LIKE "%search%"
AND tags LIKE "%webservice%"
AND tags NOT LIKE "%semweb%"

Conclusion

The advantages of this solution:

Disadvantages:
  • You have a limit on the number of tags per bookmark. Normally you use a 256byte field in your DB (VARCHAR). Otherwise, if you took a text field or similar, the query times would slow down, I suppose
  • Patrice noticed that LIKE "%search" will also find tags with “websearch”. If you alter the query to LIKE " %search% " you end up having a messy solution: You have to add a space to the beginning of the tags value to make this work.

"Scuttle" solution

Scuttle organizes its data in two tables. That table “scCategories” is the “tag”-table and has got a foreign key to the “bookmark”-table. database structure of scuttle

Intersection (AND)

Query for “bookmark+webservice+semweb”:
SELECT b.*
FROM scBookmarks b, scCategories c
WHERE c.bId = b.bId
AND (c.category IN ('bookmark', 'webservice', 'semweb'))
GROUP BY b.bId
HAVING COUNT( b.bId )=3
First, all bookmark-tag combinations are searched, where the tag is “bookmark”, “webservice” or “semweb” (c.category IN ('bookmark', 'webservice', 'semweb')), then just the bookmarks that have got all three tags searched for are taken into account (HAVING COUNT(b.bId)=3).

Union (OR)

Query for “bookmark|webservice|semweb”:
Just leave out the HAVING clause and you have union:
SELECT b.*
FROM scBookmarks b, scCategories c
WHERE c.bId = b.bId
AND (c.category IN ('bookmark', 'webservice', 'semweb'))
GROUP BY b.bId

Minus (Exclusion)

Query for “bookmark+webservice-semweb”, that is: bookmark AND webservice AND NOT semweb.
SELECT b. *
FROM scBookmarks b, scCategories c
WHERE b.bId = c.bId
AND (c.category IN ('bookmark', 'webservice'))
AND b.bId NOT
IN (SELECT b.bId FROM scBookmarks b, scCategories c WHERE b.bId = c.bId AND c.category = 'semweb')
GROUP BY b.bId
HAVING COUNT( b.bId ) =2
Leaving out the HAVING COUNT leads to the Query for “bookmark|webservice-semweb”.
Credits go to Rhomboid for helping me out with this query.

Conclusion

I guess the main advantage of this solution is that it is more normalized than the first solution, and that you can have unlimited number of tags per bookmark.

"Toxi" solution

image
Toxi came up with a three-table structure. Via the table “tagmap” the bookmarks and the tags are n-to-m related. Each tag can be used together with different bookmarks and vice versa. This DB-schema is also used by wordpress.
The queries are quite the same as in the “scuttle” solution.

Intersection (AND)

Query for “bookmark+webservice+semweb”
SELECT b.*
FROM tagmap bt, bookmark b, tag t
WHERE bt.tag_id = t.tag_id
AND (t.name IN ('bookmark', 'webservice', 'semweb'))
AND b.id = bt.bookmark_id
GROUP BY b.id
HAVING COUNT( b.id )=3

Union (OR)

Query for “bookmark|webservice|semweb”
SELECT b.*
FROM tagmap bt, bookmark b, tag t
WHERE bt.tag_id = t.tag_id
AND (t.name IN ('bookmark', 'webservice', 'semweb'))
AND b.id = bt.bookmark_id
GROUP BY b.id

Minus (Exclusion)

Query for “bookmark+webservice-semweb”, that is: bookmark AND webservice AND NOT semweb.

SELECT b. *
FROM bookmark b, tagmap bt, tag t
WHERE b.id = bt.bookmark_id
AND bt.tag_id = t.tag_id
AND (t.name IN ('Programming', 'Algorithms'))
AND b.id NOT IN (SELECT b.id FROM bookmark b, tagmap bt, tag t WHERE b.id = bt.bookmark_id AND bt.tag_id = t.tag_id AND t.name = 'Python')
GROUP BY b.id
HAVING COUNT( b.id ) =2

Leaving out the HAVING COUNT leads to the Query for “bookmark|webservice-semweb”.
Credits go to Rhomboid for helping me out with this query.

Conclusion

The advantages of this solution:
  • You can save extra information on each tag (description, tag hierarchy, …)
  • This is the most normalized solution (that is, if you go for 3NF: take this one :-)
Disadvantages:
  • When altering or deleting bookmarks you can end up with tag-orphans.
If you want to have more complicated queries like (bookmarks OR bookmark) AND (webservice or WS) AND NOT (semweb or semanticweb) the queries tend to become very complicated. In these cases I suggest the following query/computation process:
  1. Run a query for each tag appearing in your “tag-query”: SELECT b.id FROM tagmap bt, bookmark b, tag t WHERE bt.tag_id = t.tag_id AND b.id = bt.bookmark_id AND t.name = "semweb"
  2. Put each id-set from the result into an array (that is: in your favourite coding language). You could cache this arrays if you want..
  3. Constrain the arrays with union or intersection or whatever.
In this way, you can also do queries like (del.icio.us|delicious)+(semweb|semantic_web)-search. This type of queries (that is: the brackets) cannot be done by using the denormalized “MySQLicious solution”.
This is the most flexible data structure and I guess it should scale pretty good (that is: if you do some caching).

Update May, 2006. This arcticle got quite some attention. I wasn’t really prepared for that! It seems people keep referring to it and even some new sites that allow tagging give credit to my articles. I think the real credit goes to the contributers of the different schemas:MySQLiciousscuttleToxi and to all the contributors of the comments (be sure to read them!)
P.S. Thanks to Toxi for sending me the queries for the three-table-schema, Benjamin Reitzammer for pointing me to a loughing meme article (a good reference for tag queries) and powerlinux for pointing me to scuttle.
Further reading

Monday, January 27, 2014

Front-End Development: 5 Things You Should Definitely Learn in 2014

Front-End Development: 5 Things You Should Definitely Learn in 2014

A post by Joseph Howard@http://www.pencilscoop.com/2014/01/front-end-development-5-things-you-should-definitely-learn-in-2014/

We all know at what a rapid pace the world of web design and development moves. As designers and developers we are set with similar tasks of continually learning and improving to ensure we’re up to date with the latest trends, projects and practices in our continual attempt to stay relevant in such a fast-paced industry.
For front-end developers, improving on existing skills and taking on new best practices, new languages, implementation techniques and deployment are integral. However it’s very easy to fall behind, often through becoming complacent or overly protective of the workflow you’ve become so accustomed to using over the years. There’s nothing wrong with this kind of “If it aint broken, don’t fix it” attitude, however it comes at a risk – one of becoming obsolete, very quickly.
Today, the web is such a vibrant environment full of media, applications and interactivity. Sure, a simple HTML/CSS setup has worked for a long time, and will continue to do so– however we are now seeing a seemingly endless stream of innovative development and deployment projects released everyday.
Some of these are useful and develop a strong community and support network. However they almost always take a significant amount of time to become widely accepted as a recognised development practice.
One way of ensuring you’re at the forefront of the latest web development know-how is to make an active list of things you need to improve on or learn, and commit a structured time management road-map to improvement.
If you haven’t already – here are some useful things you should consider learning in 2014:

Learn and Start Using SASS

learn-SASS
You’ve almost definitely heard of SASS right? However (like a lot of people) you may be reluctant to give it a try. Let me put it this way, every developer who currently uses SASS has gone through the exact same notion you’re going through. After years of religiously following your own workflow and structuring CSS files just the way you like them – why should you change? Well, there’s heaps of reasons, all the buzz around SASS wouldn’t be for nothing right? If so many people are using it, there must be something good about it right? Exactly and there’s a lot of things – once you start using it, you’ll wonder why you didn’t earlier. Here’s a few useful links to get started:
Why SASS? – A List Apart.

Learn Grunt

learn-grunt
Maybe you’ve heard of Grunt. The name sounds kind of weird I know, but Grunt is a fantastic tool and workflow for designers and front-end developers. It runs on JavaScript and does a whole bunch of tasks for you like compiling and minifying CSS and JavaScript as well as compiling CSS from SASS. But that’s not even the start of it, Grunt can do all sorts of things  (too many to list here). It’s totally customisable and works how and when you want it to work. It says it’s a task runner – but really it’s more than that, it’s a project workflow. To get started with Grunt take a look at these two links below:
First Moments With Grunt (screen cast video) – CSS Tricks.

Learn SVG

learn-SVG-animation
You’ve probably heard all the buzz on SVG over the past few months. The truth is, SVG has been around for quite a while, but don’t ask me why it’s only taking off now. Anyway, when combined with CSS and JavaScript, SVG can produce some interesting effects and will no doubt evolve through increased interest throughout 2014. To get started, take a look at these articles:
Getting Started with SVG - Webdesign Tuts+.

Learn CSS Animation

learn-keyframing
Again, another feature that’s been around for a while. Traditionally most browser animation has been handled via jQuery, however CSS animations are becoming highly mediated lately. The debate continues as to which way of handling animations is the best, however ultimately the choice is up to you. Personally, I find CSS animations and keyframing pretty easy to use and relatively logical in general. Here are some useful links for getting started.
Intro to CSS Animations – CSS Tricks (Screen Cast)
Transitions & Animations - A Beginner’s Guide to HTML & CSS
CSS Keyframe Syntax - CSS Tricks.
Animate.CSS - A useful list of pre-made CSS animations and effects.

Learn Custom Parallax

learn-parallax
Some would say the parallax effect has already come and gone, which is probably partly true. However it’s starting to be used in some more subtle ways which can help put the finishing touches on any project. That being said, there are a lot of plugins available for parallax effects, however if you really want to master it, you should really learn create your own custom effect. Here’s some more info:

What front-end development stuff are you using at the moment? Is anything notable you would recommend? Let us know in the comments.

About The Author

Joseph Howard
Hi I'm Joseph Howard. I'm a web-designer and digital media professional and I'm the creator of PencilScoop. You can get in touch with me through your preferred social media account.

150+ Free Animated SVG Icons

150+ Free Animated SVG Icons

A post by Joseph Howard@http://www.pencilscoop.com/2013/12/150-free-animated-svg-icons/
SVG implementation is fast becoming one of the hottest topics sweeping design and development circles as of late. With all the start-ups and JavaScript libraries, I wanted to create a set of SVG icons that have zero third-party dependencies and that can be implemented easily.
I’ve already written a number of articles on SVG, including this tutorial on animating icons with simple CSS and a tiny bit of jQuery. If you’re mostly unfamiliar with SVG implementation, it’s a good place to start. For some additional reading, take a look at this article here, which looks at the comparisons between SVG and icon-fonts.
However, the idea with this article is to provide a set of icons that any web designer or developer can use. Let’s take a look at how everything’s setup.


Setup

As you can see in the demo, there are 6 different sets of icons with various differences in styling and animation. All the styling and animation is done exclusively in CSS, externally from the inline SVG mark-up. If you take a look at the source files, you’ll notice I’ve separated all the styling into individual styles-sheets for the corresponding icon style.
Let’s take a look at the general document setup:
  1. <!DOCTYPE>
  2. <head>
  3. <meta charset="utf-8">
  4. <title>150+ Animated SVG Icons Demo</title>
  5. <link rel="stylesheet" type="text/css" href="css/social_line_styles.css"><!--SVG Styles & Animation-->
  6. </head>
  7. <body>
  8. <span class="svg-icon flat-line" id="line-lightning"></span><!-- SVG icon is injected via JavaScript into span via the ID -->
  9. <script src="js/svg_inject_scoial_line.js"></script><!--SVG injection script - contains the inline SVG Data-->
  10. </body>
  11. </html>
As you can see, the setup is quite simple. The SVG mark-up is injected externally via JavaScript and styled in an external style-sheet.

SVG Injection

Let’s take a look at how the JavaScript injects the SVG into the page. The idea here is that you can use it more dynamically as you won’t need to worry about putting SVG inline SVG’s directly into the page. All you need to do is create an HTML element with the corresponding “id”, and the script will inject the SVG into that element. Additionally, I’ve included all the cleaned and optimised SVG files if you prefer to use other means of implementing.
  1. var SVGstring = "<!--SVG Mark-Up Goes Here-->";
  2. $(SVGstring).appendTo('#DIV-NAME');

The HTML

The HTML is pretty simple, the icons are injected into “<span>”s with a class for general styling and an ‘id” for specific styling and the injection.
  1. <span class="svg-icon ICON-CLASS-STYLE" id="INDIVIDUAL ID FOR INJECTION AND STYLING"></span>

The CSS

The SVG mark-up contains all the classes and path data. By default, it contains CSS styling mark-up as well. However I’ve placed this in the style-sheets and applied some basic styling and animations. If you want to get more advanced with the animations, feel free to do so.

Lastly, the flat design icons were designed by Studio4 | Creative and are free for any use, credit goes to them for the design. However I slightly modified the original designs as well as converted them to SVG (amongst other things). That’s it really. Feel free to use them to your liking.
free-animated-svg-icons
Please note, although I’ve designed this for easy implementation, you may need to make some minor adjustments in integrating it into your own set-up. Enjoy!

About The Author

Joseph Howard
Hi I'm Joseph Howard. I'm a web-designer and digital media professional and I'm the creator of PencilScoop. You can get in touch with me through your preferred social media account.