Skip to content

Instantly share code, notes, and snippets.

@robi42
Created June 16, 2011 20:35
Show Gist options
  • Save robi42/1030207 to your computer and use it in GitHub Desktop.
Save robi42/1030207 to your computer and use it in GitHub Desktop.
(function (win) {
win.$mp = win.$mp || {};
win.$mp.makeMvcPipe = function () {
var _loadStyleSheet = function (path, media, fn, scope) {
var sheet, cssRules;
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.setAttribute('href', path);
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('media', media);
if ('sheet' in link) {
sheet = 'sheet';
cssRules = 'cssRules';
}
else {
sheet = 'styleSheet';
cssRules = 'rules';
}
var successTimeoutId = setInterval(function () {
try {
if (link[sheet] && link[sheet][cssRules].length) {
clearInterval(successTimeoutId);
clearTimeout(successTimeoutId);
clearInterval(failureTimeoutId);
clearTimeout(failureTimeoutId);
fn.call(scope || win, true, link);
}
} catch (e) { }
}, 10);
var failureTimeoutId = setTimeout(function () {
clearInterval(successTimeoutId);
clearTimeout(successTimeoutId);
clearInterval(failureTimeoutId);
clearTimeout(failureTimeoutId);
head.removeChild(link);
fn.call(scope || win, false, link);
}, 15000);
head.appendChild(link);
return link;
};
var _activatePipelet = function (pipelet) {
document.getElementById(pipelet.Name).innerHTML = pipelet.Content;
var head = document.getElementsByTagName('head')[0];
for (var index in pipelet.JavascriptReferences) {
var link = document.createElement('script');
link.setAttribute('type', 'text/javascript');
link.setAttribute('src', pipelet.JavascriptReferences[index]);
head.appendChild(link);
}
};
return {
receivePipelet: function (pipelet) {
var stylesheetCount = pipelet.CssReferences.length;
if (stylesheetCount == 0) {
_activatePipelet(pipelet);
}
for (var index in pipelet.CssReferences) {
var cssReference = pipelet.CssReferences[index];
_loadStyleSheet(cssReference.Url, cssReference.Media, function (success, node) {
stylesheetCount--;
if (stylesheetCount === 0) {
_activatePipelet(pipelet);
}
});
}
}
};
};
})(window);
// Exemplary user code:
$.getJSON('/home/bannercontent', function (data) {
var pipe = $mp.makeMvcPipe();
pipe.receivePipelet(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment