Skip to content

Instantly share code, notes, and snippets.

@akhoury
Last active December 22, 2015 11:38
Show Gist options
  • Save akhoury/6466512 to your computer and use it in GitHub Desktop.
Save akhoury/6466512 to your computer and use it in GitHub Desktop.
Inject CSS and JS tag in an handlebar template
<script>
// document ready, using jquery
$(function() {
var injectScript = function(src, options) {
options || (options = {});
injectTag('script', {src: src, type: 'text/javascript'}, options);
};
var injectStyle = function(href, options) {
options || (options = {});
var img = document.createElement('img');
img.onerror = options.onload || null;
delete options.onload;
injectTag('link', {href: href, type: 'text/css', rel: 'stylesheet'}, options);
img.src = href;
};
var injectTag = function (tagName, attrs, options) {
options || (options = {});
var tag = document.createElement(tagName);
tag.onload = options.onload || null;
Object.keys(attrs).forEach(function(key) {
tag.setAttribute(key, attrs[key]);
});
if (options.insertBefore) {
options.insertBefore.parentNode.insertBefore(tag, options.insertBefore);
} else if (options.appendChild) {
options.appendChild.appendChild(tag);
} else {
var scripts = document.getElementsByTagName('script');
scripts[scripts.length - 1].parentNode.appendChild(tag);
}
};
// this is just a demo, I inject jquery-ui only if date field is not supported by current browser
var dateField = $("#datepicker");
// test if input='date' is compatible here
var elem = document.createElement('input');
elem.setAttribute('type', 'date');
if ( elem.type === 'text' ) {
// inject jquery-ui css, then js
injectStyle("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css", {
// that's the CSS onload callback
onload: function() {
injectScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js", {
// that's the JS onload callback
onload: function () {
if (dateField.datepicker) {
dateField.datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function (dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
} else {
console.log("no $().datepicker() ?");
}
}
});
}
});
} else {
dateFied.data("fellback", false);
}
});
</script>
<input title="{{this.title}}" type="text" id="datepicker" class="anniversary" value="{{#if this.anniversary}}{{this.anniversary}}{{/if}}">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment