Skip to content

Instantly share code, notes, and snippets.

@torgeir
Created January 31, 2014 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torgeir/8733249 to your computer and use it in GitHub Desktop.
Save torgeir/8733249 to your computer and use it in GitHub Desktop.
Requirejs plugin to load different resources based on some condition.
<!doctype html>
<meta charset=utf-8>
<title>requiretest</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script>
<script>
define("A", [], function () {
function A () { console.log('A') }
return A;
});
define("B", [], function () {
return function B () { console.log('B') }
});
define('conditional', function () {
return {
load: function (name, req, onload, config) {
req([name], function (value) {
onload(value);
});
},
normalize: function (name, normalize) {
if (name.indexOf("?") == -1) {
return name;
}
var split = name.split("?");
var condition = split[0];
var choices = split[1].split(":");
var dependencyNr = eval(condition) ? 0 : 1;
return choices[dependencyNr];
}
}
});
var someCondition = 1;
require(['conditional!someCondition?A:B'], function (AorB) {
new AorB; // loads A
});
//var first = 0;
//require(['conditional!someCondition?A:B'], function (AorB) {
//new AorB; // loads B
//});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment