Namespace a dynamically loaded javascript file's contents - Stack Overflow

Is it possible to namespace a JavaScript file inserted dynamically? I know that I can dynamically inclu

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().

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().

Share Improve this question edited Jun 15, 2012 at 15:03 Tim Abell 11.9k9 gold badges88 silver badges113 bronze badges asked Aug 14, 2011 at 9:35 William NiuWilliam Niu 15.9k8 gold badges57 silver badges93 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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 pliant. 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.

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745543919a4632252.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信