Skip to content

Instantly share code, notes, and snippets.

@mikeyledoux
Last active October 14, 2015 00:27
Show Gist options
  • Save mikeyledoux/4279628 to your computer and use it in GitHub Desktop.
Save mikeyledoux/4279628 to your computer and use it in GitHub Desktop.
Use this to load in a JS dependency on the fly, FROM your other js files. [usage examples at the bottom] Background: Sometimes we don't want to load every JS file we use on every page, because only certain pages use them. Sometimes we may not want to have to use our application framework make the decision about which JS file(s) to use. NOTE: Thi…
var myLIB = {
desc: 'This thing does neato stuff'
};
myLIB.init = function (lib_type, callback) {
"use strict";
if (typeof lib_type !== 'undefined'){
renderScript();
}
function renderScript() {
$.ajax({
url: 'http://[your_domain]/[your_js_directory]/' + lib_type + '.js',
dataType: 'script',
complete: function () {
if (callback) {callback();}
},
error: function () {
alert('ATTN DEV: The requested myLIB asset was not able to load. Please check the content URL before doing anything else.');
}
});
}
};
// [USAGE EXAMPLE]
// // WE'RE INSIDE OF ANOTHER JS FILE AND WE WANT TO USE
// // FUNCTIONS FROM ANOTHER JS FILE THAT WE DIDN'T WANT TO INCLUDE IN
// // THE PAGE AT RUNTIME. so WE CALL IT LIKE THIS:
myLIB = myLIB || {};
$(document).ready(function(){
"use strict";
myLIB.init('whatever_utilities');
//[OR]
myLIB.init('whatever_utilities', function(){
//loading things via the callback here ensures we won't call anything that isn't yet defined
alert('we\'ve now loaded whatever_utilities.js, let\'s do other cool stuff');
someWhateverUtilitiesFunction();
});
});
@mikeyledoux
Copy link
Author

Thanks broderboy!

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