Skip to content

Instantly share code, notes, and snippets.

@imjakechapman
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save imjakechapman/8983290 to your computer and use it in GitHub Desktop.

Select an option

Save imjakechapman/8983290 to your computer and use it in GitHub Desktop.
Conditional script loading based on declarative markup
require.config({
baseUrl: '/assets/js',
paths: {
jquery: [
'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min',
'vendor/jquery'
],
slider: 'vendor/slider',
player: 'vendor/player'
}
});
// Load the main app module to start the app
requirejs(["main"]);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Conditional Script Loading Demo</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- normalize.css - thanks necolas! -->
<link rel="stylesheet" href="http://necolas.github.io/normalize.css/3.0.0/normalize.css">
</head>
<body>
<h1>Conditional Script Loading Demo</h1>
<div data-feature="player"></div>
<div data-feature="slider"></div>
<script data-main="/assets/js/app" src="/assets/js/require.js"></script>
</body>
</html>
define(["jquery"], function($) {
//the jquery.alpha.js and jquery.beta.js plugins have been loaded.
$(function() {
// initialize all required feature scripts based off of data-feature attribute of an element
// Require.js will not reload duplicate modules
$('*[data-feature]').each(function(i, el) {
var feature = $(el).data('feature');
// require feature
require([feature], function(feature) {
feature.init();
});
});
});
});
define(["jquery"], function($){
"use strict";
function init() {
console.log('player is ready for use');
}
return {
init: init,
};
});
define(["jquery"], function($){
"use strict";
function init() {
console.log('slider is ready for use');
}
return {
init: init,
};
});
@imjakechapman
Copy link
Author

@davidhemphill I've actually changed it a bit after viewing some code from another website that I think is rock solid in their code organization.

It took a little bit of time to get use to what goes where and how you actually use the single js files, but now I love it. Still a little confusing using non AMD code, after figuring out shims correctly though its a breeze now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment