David Fariña
David Fariña

Reputation: 1594

Load Javascript like PHP's include

Today im asking for something, that i cant believe to find on the web.

Im trying to make a javascript function, which allows me to give a filename/pathname as a parameter and the function returns javascript code which will be executed/initialized immediatly - just like PHP's include or require.

Now i tried several technics to realize my approach but i just dont hit the right spot so i might be asking: is it even possible to do that in JS?

Thanks in advance

Upvotes: 0

Views: 2536

Answers (1)

razorbeard
razorbeard

Reputation: 2944

There are many libraries and standards that exist merely for this purpose. In Node.js, there is a CommonJS implementation built-in. If you want to export a piece of code from a file, or the entire contents of a file, you can attach it to the module.exports or simply exports object. You may then use require('./path/to/file'); to require it in a separate piece of code.

Some libraries try to borrow this approach and implement it on the client side, browserify being one of them.

However, it would do you better to have a look at the best client-side library of them all: RequireJS

RequireJS implements what is called the Asynchronous Module Definition pattern, which loads in all the project dependencies in a top-level file. It gives you access to two functions, require() and define() that take a number of paramaters. The first function simply requires dependencies, while the second one defines a module and name's that modules dependencies, like so:

A top-level file that defines no modules, only uses them:

require(['jquery', 'underscore', 'backbone'], // dependencies
  function($, _, Backbone) { // dependencies are passed into callback
    $('div').append('Test'); // dependencies are available to this file
  }
);

A module:

define(['jquery', 'underscore', 'backbone'], // this module's dependencies
  function($, _, Backbone) { // dependencies are made available
    var MyModule = {};
    return MyModule; // this return statement essentially defines the module
  }
);

The great thing about this approach is that by having a top level file and several modules that all define their own dependencies, you only ever need to reference a module if it actually is a dependency of that file, so your top-level stuff is always neat and uncluttered and usually consists of no more than an initialize function.

RequireJS also comes with an optimizer called R.js that can minify and concatenate your scripts in the right order using UglifyJS or Google's Closure Compiler. It's worth checking out.

Upvotes: 2

Related Questions