In many places in the html AssetsManager.registerAssets(...) can be called.
The problem is: when
if (isAllAssetsLoaded()) { notify(); }
is executed (when JS is loaded) the
assetsCount
and
assetsLoaded
values can be changed by other calls of
AssetsManager.registerAssets
.
I thought to create URLS_Array that will be like dictionary. The key will be the url and the value will be
{assetsCount = "..", assetsLoaded= ".."}
and when
if (isAllAssetsLoaded()) { notify(); }
will be executed, the appropriate element will be fetched from URLS_Array by url(like
URLS_Array[url]
). The question is when this
assetsLoaded++;
if (isAllAssetsLoaded()) {
notify();
}
is executed, how I know to which JS it belongs?
If someone has other ideas how to do it without URLS_Array, so I'll be glad to here
My code
var AssetsManager = function ($) {
observers = [];
assetsCount = 1;
assetsLoaded = 0;
function registerAssets(assets) {
assetsCount = assets.length;
$.each(assets, function (index, asset) {
if (asset.type == "script") {
registerJS(asset.url);
}
else if (asset.type == "stylesheet") {
registerStyle(asset.url);
}
});
}
function registerJS(url) {
var head= document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
script.type = "text/javascript";
$(script).load(function () {
assetsLoaded++;
if (isAllAssetsLoaded()) {
notify();
}
});
head.appendChild(script);
}
function registerStyle(url) {
var head= document.getElementsByTagName("head")[0];
var style = document.createElement("link");
style.href = url;
style.type = "text/css";
style.rel = "stylesheet";
head.appendChild(style);
}
function isAllAssetsLoaded() {
return assetsCount == assetsLoaded;
}
function notify() {
$.each(observers, function (index, func) {
func();
});
observers = [];
}
return {
RegisterJS: function (url) {
registerJS(url);
},
RegisterStyle: function (url) {
registerStyle(url);
},
RegisterAssets: function (assets) {
registerAssets(assets);
},
AttachObserver: function (o) {
observers.push(o);
}
}
} (jQuery)