简体   繁体   中英

Runtime loading Modular JavaScript without script tag or DOM

I'm working with an application wrapper that provides only a psuedo-DOM. No support for tags. I like AMD modules and have used RequireJS in the past, but understand that it uses script tags to inject code. Plus, at this time I don't want to optimize code to a single file, so I'm looking for a way to load modules at runtime without using script tags. Preferably, I'd like to use AMD module pattern and be able re-use much of the same code within a 'normal' browser-based app.

eval() seems to be the answer, but I wanted to ask. Is there a better way?

The most viable option i can think of would be the Almond version of RequireJS and XHR+eval but if that is a really viable option is highly dependent on the target environment.

With this combination (Almond+XHR+eval) you will have to add your own loader because Almond doesn't have a script-loader and depending on how browser-like the wrapper is you talk about, you can replace it with a custom written one or with one of the script-loaders that are already out there like yepnope, jquery's getScript() or LABjs.

some extra info: RequireJS's use of script tags is because of much better support (when compared to eval) and for debug purposes. Eval has its security problems and is not really consistent between environments because of the context in which it executes the eval'ed code (sometimes global sometimes where you call the eval) and sometimes eval isn't available at all.

The post Reusing require.js modules in Node.js shows how to use AMDrequire to reuse browser code into server code. You don't mention anything about node.js but probably you can find a workaround using this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM