Search code examples
requirejsamd

Feed Javascript directly into RequireJS Require function


We have require implemented in our web app and is working a treat. The change up now is that we have some javascript that is dynamically created at runtime on the client. Is there a way with require to directly inject a string of javascript directly into the require() function.

Currently we have:

 require([moduleToLoad], function(mod){ //DO SOMETHING}});

Want something like (forgive the syntax because just writing it out):

var jsString = "define(['Text!something.htm'], function (control_Template) { //MODULE LOADED JAVASCRIPT}))";
require(jsString, function(mod){ //DO SOMETHING}});

Does anyone know how and if we can accomplish this?

Thanks


Solution

  • You can use named modules syntax in your string for defining the AMD module. Eval this string and then require the module using the name you have provided.

    Define module like following

    eval("define('runtimemodule', ['Text!something.htm'], function(){ return 'template here' })")
    

    Require module like following

    require(["runtimemodule"], function(mod){ 
       console.log(mod); //logs "tempalte here"
    });