0
votes

Im starting now with RequireJS and im trying to require modules conditionaly.

Basically what i want to do is:

  • Require jQuery.
  • Check if have a element with X data tag. $('[data-myplugin]').length > 0
  • If true, require the myplugin plugin
  • After loaded, star myplugin $('[data-myplugin]').myplugin()

There is a way to do this with RequireJS?

Is this a good approach?

1

1 Answers

0
votes

you can write your main.js like bellow:

var reqs = ["jquery"];

/* you must make sure that the '$'(jquery already loaded) can be used.
 * or you should use pure javaScript code to do the test */
if($('[data-myplugin]').length > 0) {
    reqs.push("myplugin");
}

require( reqs,

function() {
    if($('[data-myplugin]').length > 0) {
        $('[data-myplugin]').myplugin();
    }
});