Optimize your JavaScript with RequireJS

Default avatar.
February 11, 2013
Optimize your JavaScript with RequireJS.

ThumbnailRequireJS is an effective way to improve the speed and quality of your JavaScript code additionally making it a lot more readable and easier to maintain.

In this article I'll introduce you to RequireJS and how you can begin using it. We will go through requiring files and defining a module and even touch on optimization.

In simple terms require.js is a script loader that allows you to slip your JavaScript code into files and modules thus managing the dependencies of each model.

Requiring Files

To start working with RequireJS and its Asynchronous Module Definition (AMD) we must first download it, then link to the require.js file in the head of our document like so:

<script src="require.js" data-main="main"></script>

You may be wondering what that data-main attribute is, well using RequireJS means that when you call require in the head of your document you are also linking to the main file of your JavaScript application, the data-main attribute is a link to the main JavaScript file for your application, in this case main.js. (Note that RequireJS automatically adds the .js at the end of the filename.)

In this main.js file you will place the configuration for RequireJS, load in your modules and define a base path for use when requiring files.

The Require Function

RequireJS uses a simple require function to load in scripts, in this example RequireJS loads jQuery:

require(["jquery"], function($) {
return $(‘#mydiv”).html(‘Hello this is RequireJS talking”);
});

One of the best things about RequireJS is that it is extremely readable, if you look at that block of code you will see that first require grabs the file with the name of jquery.js and it passes an anonymous function with jQuery’s $ as a parameter, when that is done you are free to use all the JQuery code you please.

Now, you normally wouldn't have the jQuery library in a file named jquery.js, as with most plugins and frameworks, we normally choose to load then from their GitHub or the Google CDN, and for that we need to configure the paths so that they point to the right place:

require.config({
paths: {
"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"
}
});

This means you can require jQuery via Google and use it without a problem. (Note that I've used the name "jquery" in this example, but you could call it anything you like.)

Defining a module

Using the AMD pattern means that our code can be structured in modules; these models are just bits of code that do something in our application. You can place two lines of code in a module or 100, it just depends on what you want that module to do.

To define a module we use code like this:

define(function () { 
function add (x,y) {
return x + y;
}
});

In this example I have created a simple add function with no dependencies, but if this function needed jQuery to work properly, the define function would be structured like this:

define([‘jquery’], function () { 
function place(mydiv) {
return $(mydiv).html(‘My Sample Text’);
}
});

Using this syntax we tell JavaScript to go get jQuery first, and then run the code so that jQuery is available when needed. We can also use this in modules we have written in JavaScript files, it’s not limited to frameworks or plugins.

Optimization

As you can see RequireJS is a great tool for organizing your files into modules and only loading what you need. The downside is that too many JavaScript files result in poor load times, which is why RequireJS includes an optimizer to collect the data from all the files and place it in a single minimized file.

All in all, RequireJS is one of the best ways to organize and optimize your JavaScript for the modern web.

Have you used RequireJS in a project? Has it improved your workflow? Let us know in the comments.

Featured image/thumbnail, boxes image via Shutterstock.

Sara Vieira

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website.

Read Next

24 Best Creative Portfolio Websites in 2023

For anyone working in a digital creative field, whether design, illustration, animation, video, or a combination of…

15 Best New Fonts, September 2023

Nothing upgrades your designs like selecting the right font. It’s all too easy to fall into the trap of using the same…

Weekly Design News #1

Every Sunday we’re rounding up the best of the previous week’s stories from webdesignernews.com, and in this issue #1,…

The 20 Most Controversial Logos of All Time (Ranked)

When you hire graphic designers to create your company's logo, what do you expect? Professional designs, culturally…

LimeWire AI Studio Generative Art App

If you’re looking for the most exciting way to launch a career in AI-generated art, then you’re in the right place.

20 Best New Websites, September 2023

Are you in need of design inspiration? Are you looking for the best websites designed in 2023 to pull ideas,…

The Dangers of Deceptive Design Patterns (And How to Avoid Them)

As web designers, our role in crafting user-friendly digital landscapes is critical. We are tasked with creating user…

10 Best Ecommerce WordPress Themes in 2023 [September update]

You plan to set up shop with an online store. You know there’ll be competition. And to compete with or beat that…

5 Marketing Tools Every Designer Needs

Yes, designers do need marketing tools. From freelance graphic designers who need to land more work to designers who…

Exciting New Tools For Designers, September 2023

At the end of another summer, we are all getting ready to knuckle down for some serious work in the fall. But we want…

Elon Musk calls LinkedIn ‘Cringe’—Announces Competitor

Elon Musk recently announced his intentions to create a direct competitor to LinkedIn. Musk’s grand plan is to make his…

Everything You Need to Know to Embrace the Y2K Design Trend

The turn of the millennium was a major cultural shift, and the Y2K aesthetic emerged as a visualization of what the…