0

I'm trying to dynamically load css file using javascript, and for a moment i'we think it works. But in the next moment i realise, that elements on page didn't get "width" from css file. Everything else work's ok. I check css in chrome browser from same page and it is fully loaded. What have i done wrong?

Script for load css/js files(i found it on web):

function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
    }
}

And the other jquery code:

$(this).addClass('iG_Main');
loadjscssfile(data.theme_url,'css');
createGrid($($(this).selector+'.iG_Main'));

function createGrid( selector ){
    var cellWidth, columnValue;
    var blank = ' ';


    selector.append('<div class="iG_Header"></div>');
    selector.append('<div class="iG_Container"></div>');
    selector.append('<div class="iG_Footer">This is footer!</div>');
    selector_header = selector.children('.iG_Header');
    selector_container = selector.children('.iG_Container');
    selector_footer = selector.children('.iG_Footer');
    selector_header.append('<div class="iG_Cell iG_CheckBox inHead"><div id="iG_CheckBox">'+ blank +'</div></div>');

    if(undefinedVal(data.width))
        data.width = 1000;
    if(undefinedVal(data.height))
        data.height = 400;

    for(var i in data.headerData)
        selector_header.append('<div id="'+ data.headerData[i].name +'" class="iG_Cell inHead"><div>'+ data.headerData[i].label +'</div></div>');

    if(data.options){
        selector_header.append('<div class="iG_Cell Options inHead"><div>'+ blank +'</div></div>');
    //  cellWidth = (data.width-40-15)/(data.headerData.length);
        cellWidth = (data.width-$('.iG_Cell.inHead.Options').width()-selector_header.children('.iG_CheckBox').width())/(data.headerData.length);
    }else cellWidth = (data.width-15-selector_header.children('.iG_CheckBox').width())/(data.headerData.length); //15 - in sake of scrollbar
    //}else cellWidth = (data.width-15-40)/(data.headerData.length); //15 - in sake of scrollbar

    for(var i in data.contentData){
        selector_container.append('<div class="iG_Content"></div>');
        selector_container.children('.iG_Content:last-child').append('<div class="iG_Cell iG_CheckBox inContent"><div id="iG_CheckBox">'+ blank +'</div></div>');
        for(var j in data.headerData){
            columnValue = (undefinedVal(data.contentData[i][data.headerData[j].name])) ? blank : data.contentData[i][data.headerData[j].name];
            selector_container.children('.iG_Content:last-child').append('<div class="iG_Cell"><div>'+ columnValue +'</div></div>');
        }


    selector.css({'width':data.width, 'height':data.height});
    selector_header.children('.iG_Cell').not('.Options').not('.iG_CheckBox').css('width',cellWidth);
    selector_container.children('.iG_Content').children('.iG_Cell').not('.iG_CheckBox').css('width',cellWidth);
    selector_container.css('height', data.height-selector_header.height()-selector_footer.height());
}
Clem
  • 11,334
  • 8
  • 34
  • 48
  • CSS is loaded asynchronously, so your code might be executed before css fully loaded and applied. Try to wrap your `createGrid` call in `setTimeout` for a few seconds to test this issue? – Inferpse Nov 23 '12 at 09:18
  • ok using setTimeout() i call createGrid() function. It works that way. But this is not the best way, am i right? How to avoid this? thanks – Clem Nov 23 '12 at 09:23
  • Added an answer with code example. – Inferpse Nov 23 '12 at 09:38

2 Answers2

1

Since the way you load the CSS is asynchronously from your JS execution it may happen that the code is executed before the CSS is loaded.

To avoid such issues I would create an inline style, do an XHR request to the CSS file and put the contents to the style element, e.g. like that:

$.get(the_url, function(response) {
  $('head').append('<style id="the_theme"></style>');
  $('#the_theme').text(response);

  // do the rest
});

Edit: Of course this can cause problems with relative URLs with are now relative to your document and no longer to your CSS file. If this is a problem for you you have to do it the complicated way: check the rule length in an interval:

cssLoaded = 0;
var iv = window.setInterval(function() {
  var cssStylesheet = document.getElementById("the_link_element");
  if(cssStylesheet.sheet && cssStylesheet.sheet.cssRules.length > 0) {
    cssLoaded = 1;
  }
  else if(cssStylesheet.styleSheet && cssStylesheet.styleSheet.cssText.length > 0) {
    cssLoaded = 1;
  }
  else if(cssStylesheet.innerHTML && cssStylesheet.innerHTML.length > 0) {
    cssLoaded = 1;
  }

  if(cssLoaded) {
    window.clearInterval(iv);
  }
}, 500);
ckruse
  • 9,642
  • 1
  • 25
  • 25
1

Look at this question. Using code from accepted answer may help. So your code will look like following:

var currentItem = $(this);
currentItem.addClass('iG_Main');
loadStyleSheet( data.theme_url + '.css', function( success, link ) {
    createGrid($(currentItem.selector+'.iG_Main'));
});
Community
  • 1
  • 1
Inferpse
  • 4,135
  • 1
  • 31
  • 39