Need help?

I'm available for remote short term contracting or consultancy work. Please check out my LinkedIn profile for more details on my experience.

Please feel free to use the form below to contact me.




How to include files using JavaScript like PHP does

Are you looking to find out how to include/require files on the fly using JavaScript? That's what we're going to go through in this article. The same functionality used in PHP to require/include other PHP files can just as easily be done in JS.

Before we can start, we have to download a JS library called RequireJS - this allows us to load files and modules asynchronously using JavaScript.

You can download the RequireJS here.

The biggest strength of RequireJS, is the ability to load custom modules directly from another file - this is done using their load defined syntax. Lets start by walking through the basics - here is an example of how you'd load require.js.


<!DOCTYPE html>
<html>
    <head>
        <title>Test Project</title>
        <script data-main="js/main" src="js/require.js"></script>
    </head>
    <body>
        <h1>Test Project</h1>
    </body>
</html>

In the example above, we load require, and also set the data-main as your 'main' javascript file. This tells RequireJS that main.js is the first file that should be loaded. Now that we have that in place, lets take a look at main.js.


// this will look in js/ for util.js and load it
require(["util"], function(util) {
    // once util.js is loaded, this gets called

	// getVersion is going to return a string with "ver. 5"
    console.log(util.getVersion());
});

Now that you know how to load modules/files, lets take a look at util.js.


define(function() {
    return {
        getVersion: function() {
        	   return "ver. 5";
        }
    }
});


If you don't want to use modules, you can just do the same thing using require, but just don't provide the anonymous function with a parameter. Hope this helps someone out there.


jon | August 22, 2012 | Comments (0)

Comments


Name (required)
Email (will not be published) (required)
Website

captcha