JSFiddle - React, Tailwind, and code Playground
HTML
<!-- Complex multiple script dependency management using jQuery.when() -->
<!-- blog.kevinchisholm.com -->
<script type="text/javascript" src="https://raw.github.com/janl/mustache.js/master/mustache.js"></script>
<script type="text/javascript" src="https://raw.github.com/sdellow/jQuery-Form-Validation/master/jquery.form-validation.js"></script>
<div id="container">
<h1>jQuery.when() Example</h1>
<h2>Complex multiple script dependency management</h2>
</div>
CSS
body{font: 12px Arial;}
form div{margin-bottom: 5px;}
label{display:block;font-weight:bold;}
input,{width:100%;padding:4px;border-radius:2px;border:1px solid #999;}
#container {width:400px;margin:50px auto 0;padding:22px;background-color:#ededed;border:1px solid #ccc;-webkit-border-radius:05px;-moz-border-radius:05px;border-radius:05px;}
.val-box{color:red;}
.val-message{display:none;}
input.alert.error{border:1px solid red;}
JavaScript
var
mustacheJsUrl = 'https://raw.github.com/janl/mustache.js/master/mustache.js',
jqformValUrl = 'https://raw.github.com/sdellow/jQuery-Form-Validation/master/jquery.form-validation.js',
data = {
fieldName: "first_name",
label: "First Name",
submit: "Submit this form",
error: "Please be sure to enter your first name"
},
template = ''
+ '<form id="testform">'
+ '<div class="field">'
+ '<label for="{{fieldName}}">{{label}}</label>'
+ '<input type="text" id="{{fieldName}}" name="{{fieldName}}" class="required">'
+ '<button type="submit">{{submit}}</button>'
+ '<div class="val-message">{{error}}</div>'
+ '</div>'
+ '</form>',
confirmFormVal = function (){
//is jquery.form-validation.js loaded on this page?
if(!jQuery.fn.formval){
//if not, load it
return $.when($.getScript(jqformValUrl));
} else {
//it's loaded, just return the resolved jQuery deferred object
console.log('formval is already loaded...');
return jQuery.Deferred().resolve();;
};
},
confirmMustacheJs = function (){
//is mustache.js loaded on this page?
if(!window.Mustache || !window.Mustache || !window.Mustache.name === 'mustache.js'){
//if not, load it
return $.when($.getScript(mustacheJsUrl));
} else {
//it's loaded, just return the resolved jQuery deferred object
console.log('Mustache is already loaded...');
return jQuery.Deferred().resolve();
};
},
formValIsLoaded = confirmFormVal(),
mustacheIsLoaded = confirmMustacheJs();
$.when(formValIsLoaded,mustacheIsLoaded).done(function(){
//build the markup fom the template (uses Mustache.js)
var form = Mustache.render(template,data);
//inject the form
$('#container').append(form);
//setup the form for validation (form validation plugin)
$('#testform').formValidation();
});