10

Is it possible to namespace a JavaScript file inserted dynamically?

I know that I can dynamically include a JavaScript file by creating a script tag and insert it into the DOM, but can this included file be namespaced? So, if the file has a function called bar, I would want access it through a namespace, say foo: i.e. foo.bar().

Tim Abell
  • 11,186
  • 8
  • 79
  • 110
William Niu
  • 15,798
  • 7
  • 53
  • 93

2 Answers2

6

Yes, CommonJS Modules/1.1 specifies only one way of doing it.

I've used it only with Node.js on server side, but I believe there are other libraries created to work with browser that are CommonJS compliant. Beware that there are multiple module specifications for server/browser (didn't dig into that yet).

Modules are written just like any other piece of javascript, the only addition is you export what you want to expose:

module.exports.bar = Bar;

function Bar() {
 // code
}

And the usage:

var foo = require('mymodule');

foo.bar();

What is actually done in the background, the whole code is wrapped into another function and exports are its properties.

Also, Michael Bolin talked about similar problem in his talk about 'with' keyword at JSConf.

usoban
  • 5,428
  • 28
  • 42
  • 1
    CurlJS, requireJS support AMD modules which are similar and work out of the box on the browser. Tools like browserify allow you to create Modules/1.1 bundles. – Raynos Aug 14 '11 at 11:27
  • 1
    I still haven't got around playing with this. One question though, does each included js file need to export the properties for the `require` to pick them up? If that is the case, how do I achieve namespacing when including third-party js file? – William Niu Aug 18 '11 at 23:00
  • So how do you do it without using a library? – Cypher Dec 16 '14 at 23:27
0

If you mean to add a namespace to everything that is defined in that file while loading it dynamically, without modifying the file itself, the answer is no.

Dan Mazzini
  • 1,005
  • 10
  • 19