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
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • By
    Google Extension Effect with CSS or jQuery or MooTools JavaScript

    Both of the two great browser vendors, Google and Mozilla, have Extensions pages that utilize simple but classy animation effects to enhance the page. One of the extensions used by Google is a basic margin-top animation to switch between two panes: a graphic pane...

  • By
    CSS Fixed Position Background Image

    Backgrounds have become an integral part of creating a web 2.0-esque website since gradients have become all the rage. If you think gradient backgrounds are too cliche, maybe a fixed position background would work for you? It does provide a neat inherent effect by...

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!