Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load html content dynamically with RequireJS

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?

like image 926
Dareon Avatar asked Nov 19 '25 06:11

Dareon


1 Answers

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

like image 187
Nikos Paraskevopoulos Avatar answered Nov 20 '25 18:11

Nikos Paraskevopoulos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!