...let John help you code



how to load static components in a page using JStaticLoader

Asked by:
qAsker
Nov 25, 2016, 15:59

1 Answer

Answer :
Code

Preview
 

0

You can still use JStaticLoader in your app as a directive, direct call it from your controller or even in the $rootScope to load your desired js.
It uses XMLHttpRequest to load the static files.
For example use in your app.js (on $routeChangeStart or $stateChangeStart )
myApp
.run(['$rootScope', '$http', function ($rootScope, $http) {
var scriptExists = function (scriptId) {
if (document.getElementById(scriptId)) {
return true;
}

return false;
};

var addLazyScript = function (scriptId, url) {
if (scriptExists(scriptId)) return;

var js = document.createElement('script'),
els = document.getElementsByTagName('script')[0];

js.id = scriptId;
js.src = url;
js.type = "text/javascript";

els.parentNode.insertBefore(js, els);
};

$rootScope.$on('$routeChangeStart', function (e, current) {
if (current.controller === 'MainCtrl') {
var pathUrls = ["https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/js/materialize.js"],
scriptId = 'lazyScript1';

if (scriptExists(scriptId)) return;

JStaticLoader(pathUrls, { files: ['js'] }, function (vals, totalTime) {
/* Success */
for (var i = 0; i < vals.length; i++) {
var path = vals[i];
addLazyScript(scriptId, path);
}
}, function (error, totalTime) {
/* Error */
console.warn(error, totalTime);
});
}
});
}]);


The code above gets a js file by using xhr , and append it as a script in the document once it's finished. The script will then be loaded from the browser's cache.
jsPat