Frage

I want to load a html content with RequireJS like this:

define(function (require) {

"use strict";

return function (id) {
     var url = 'text!screens/' + id + '.html';
     var html = require(url);
}; });

But I get this error: Error: Module name "text!screens/home.html_unnormalized2" has not been loaded yet for context: _

If I try it in this way:

define(function (require) {

"use strict";

return function () {
     var html = require('text!screens/home.html');
}; });

everything is ok. But this approach isn't very nice due to hardcore tipped url. How can I solve this?

War es hilfreich?

Lösung

Inline parametric require calls can only run asynchronously for modules that have not been loaded yet, as is your case. The principle is (also note url is in an array):

var url = 'text!screens/' + id + '.html';
require([url],
    function(text) {
        // use text
    },
    function(err) { // OPTIONAL BUT GOOD PRACTICE
        // handle error
    }
);

This has the inconvenience of not beign able to return the value immediately. Also take a look at the principle of promises (implemented by many libraries, jQuery too).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top