Load MooTools Classes on Demand with RequireJS

By  on  

RequireJS is a hugely popular JavaScript project right now thanks to what it does:  asynchronously load JavaScript files and properly handle their introduction to a namespace flawlessly.  Of course, callbacks are provided which allow you to work with the new code one it has been loaded.  MooTools is a perfect match for RequireJS because of its modular structure.  Let me show you how you can lazy load MooTools classes with the robust RequireJS library.

Grabbing and Using RequireJS

You'll obviously need to download RequireJS from the RequireJS website.  Once the file is in place on your server, place it within the page via the traditional method, a SCRIPT tag:

<script src="require.js"></script>

Now you have the power of async JavaScript loading within the page!

Using RequireJS with MooTools

With RequireJS available, all you need to do is use the require function, passing an array of files and a callback to execute once all of the files have loaded:

//require ScrollSpy and Roar
require(['scrollspy.1.2.js','Roar.js'],function(){
	//callbacks
});

Once the classes have been loaded, I can use them!  Check it out:

// require ScrollSpy and Roar
require(['scrollspy.1.2.js','Roar.js'],function(){
	//use them!
	var roar = new Roar();
	var spy = new ScrollSpy({
		onEnter: function() {
			//....
		}
	});
});

How about a practical usage?  If an element with a "lazyload" CSS class exists, load LazyLoad and create an instance:

//when the DOM is ready
window.addEvent('domready',function(){
	//find image to lazyload
	var scrollspyElements = $$('.lazyload');
	//if there are images to lazyload...
	if(scrollspyElements.length) {
		//require the class and when done...
		require(['lazyload.js'],function(){
			//create a LazyLoad instance and use it!
			new LazyLoad({
			    range: 200,
			    image: 'Assets/blank.gif',
			    elements: $$('.lazyload')
			});
		});
	}
});

Not only do you load individual classes with RequireJS, but you can also nest require calls to load MooTools asynchronously! Once MooTools is ready, you can make your checks and load MooTools classes:

//load mootools with RequireJS!
require(['mootools-1.2.4.js'],function() {
	//when the DOM is ready
	require.ready(function(){
		//find image to lazyload
		var scrollspyElements = $$('.lazyload');
		//if there are images to lazyload...
		if(scrollspyElements.length) {
			//require the class and when done...
			require(['lazyload.js'],function(){
				//create a LazyLoad instance and use it!
				new LazyLoad({
				    range: 200,
				    image: 'Assets/blank.gif',
				    elements: $$('.lazyload')
				});
			});
		}
	});
});

Awesome!  The future of JavaScript is loading components (or even a whole framework) only if you need them!

require.ready!

If you aren't using a JavaScript framework, RequireJS provides a ready method to trigger a function when the DOM is ready!

// require ScrollSpy
require(['scrollspy.1.2.js','Roar.js'],function(){
	//use it when the dom is ready!
	require.ready(function(){
		//use them!
		var roar = new Roar();
		var spy = new ScrollSpy({
			container: document.id('someDiv'),
			onEnter: function() {
				//....
			}
		});	
	});
});

This is much like MooTools' domready event and Dojo and jQuery's ready method.

RequireJS and Other Frameworks

Dojo currently contains its own asynchronous resource loading system but is looking toward the possibility of implementing RequireJS near its 2.0 release.  The RequireJS website also provides detailed instructions on using RequireJS with jQuery.

Recent Features

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

Incredible Demos

  • By
    MooTools-Like Element Creation in jQuery

    I really dislike jQuery's element creation syntax. It's basically the same as typing out HTML but within a JavaScript string...ugly! Luckily Basil Goldman has created a jQuery plugin that allows you to create elements using MooTools-like syntax. Standard jQuery Element Creation Looks exactly like writing out...

  • By
    Image Data URIs with PHP

    If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves...

Discussion

  1. Great Post!! -i’ve been looking out for something like this! thank!

  2. Hi David, nice article, but I’m biased as the main developer for RequireJS.

    One thing to note: using window.addEvent('domready',function(){}) may not trigger at the right time if you load lots of scripts with RequireJS. Since the scripts are loaded async, they do not block DOM rendering, so the DOMContentLoaded or similar approximation in IE may fire before all the scripts have executed.

    require.ready() listens for DOMContentLoaded equivalents but also waits to trigger the ready callbacks until all the scripts that RequireJS is tracking have loaded too. So it is suggested to use require.ready() to get dom ready functionality that is async loading-aware.

    • Great point James — thank you for commenting and keep up the great work!

  3. David, demo link is 404 :(

  4. I dont know why but LABjs has been there before and no body ever mentions it http://labjs.com/documentation.php

    I think it deserves some credit too!

  5. Hey,
    I’m happy with using LazyClass (http://mootools.net/forge/p/lazyclass) except it doesn’t allow using dot character in the class names (Fx.Glow). It loads specified classes only triggered by a call which is pretty handy. Really cool for asynchronous loading MT More classes which you prepare using More builder. I’d appreciate an article how it compares to requireJS or MooTools Asset.javascript class or even matrix comparison if you feel like :)

  6. Love having the ability to do this, but personally, I think this is something that should be more for webapps than websites. We’re entering another age of watching file sizes again for the mobile crowd, and that should include HTTP requests, IMHO.

    That said, this is a very cool library. ^_^

  7. ooppss .. perhaps i need to read more about RequireJS after read on this articles. Thanks for sharing.

  8. I would like to see syntax like this:

    var myClass = new Class({
    Requires: "My.Class.To.Require", //string or array
    Extends: "My.Widget.Tooltip", // check by default is this class loaded
    });

    I have found this extension http://mootools.net/forge/p/namespace and i am checking it right now

  9. Lee

    It would be helpful if you could walk through a MooTools class defined as a require.js module

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!