2010年1月23日土曜日

Dynamically Loading CSS using Javascript

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
I needed to load CSS via Javascript, to make blog parts.

The main idea is a making link element with Javascript. But it is not enough, since css is not always ready when control is back. So, I put some code which prefetches css using ajax. After successful loading of css, it makes a link element for css, then it calls setTimeout to make sure css is applied to DOM.


function loadCSS(src, delay, onload, error){
$.ajax({
type: "GET",
url: src,
dataType: 'text',
success: function(data, dataType){
debug('inserting ' + src);
var link = $('<link rel="stylesheet" type="text/css" href="'+ src+ '" />');
$("head").append(link);
setTimeout(function(){
onload();
},
delay);
},
'error': error,
});
};

$(document).ready(function(){
loadCSS('some url of css', 1,
function(){
debug('do some thing using dynamically loaded css.');
},
function (XMLHttpRequest, testStatus, errorThrown){
debug('css load failed');
});

0 件のコメント: