Introducing Sanddollar - Lightweight $(onready) Memoizer for jQuery

Introducing Sanddollar - Lightweight $(onready) Memoizer for jQuery
By jchris in Coding 2 months ago.

Of course, we’re all already familiar with the front-end performance gains of putting your Javascripts at the bottom of the page but this can be inconvenient. Sometimes it’s just easier to put a little $(onready) action in the middle of a page – eg: so I can include form-validation logic in the same partial as the form itself. (I think this still counts as progressive enhancement.)

The problem is that without $() defined in the head of your page, you’ll get errors adding onready callbacks to jQuery – and we especially want to hold back script src tags until the bottom of the page. Blocking rendering + an extra http request … but there’s a alternative! We can have our cake and eat it too.

Introducing Sanddollar

This is all that goes in your document head:

<script type="text/javascript" charset="utf-8">
  var $sanddollars=[],$=function(cb){$sanddollars.push(cb)};
</script>

And then after you’ve included jQuery.js, (just before the closing body tag, or in your jquery.extras.js file) include this callback to activate your stored functions:

<script type="text/javascript" charset="utf-8">
$(function(){$.each($sanddollars,function(){$(this)})});
</script>

Like magic, any $() callbacks you have peppered through the page will be picked up and used by jQuery, even though you include it last!

This is just something I came up with to solve a problem on Grabb.it today. I was happy to get it done so simply. Maybe there are other implementations of the same idea out there. Let me know if you spot any!

Be the first to comment on Introducing Sanddollar - Lightweight $(onready) Memoizer for jQuery

Post a comment