In the development of my app, I am faced with the challenge of dynamically loading CSS and JS. Currently, the solution looks like this:
myapp.loadCss = function(css){
$("head").append("<link>");
cssDom = $("head").children(":last");
cssDom.attr({rel: "stylesheet",
type: "text/css",
href: css
});
}
myapp.loadJs = funciton(js){
...
//$.ajax call is used in synchronized mode to make sure the js is fully loaded
}
}
When certain widgets need to be loaded, the typical calls are as follows:
myapp.loadCss('/widgets/widget1/css/example.css');
myapp.loadJs('/wiggets/widget1/js/example.js');
However, occasionally (1 out of 10 or 20 times), the newly created dom elements from example.js fail to retrieve their CSS from example.css. It appears that my loadCss method may not be loading the CSS in a synchronized manner. To address this, I attempted replacing my loadCss function with the following code:
myapp.loadCss(css){
$('<link href="' + css + '" rel="stylesheet" type="text/css" />').appendTo($('head'));
}
This seemed to resolve the issue (after multiple webpage refreshes for confirmation :-() However, this alternate method did not work in IE7 (and has not been tested in IE6 or IE8).
Are there any better solutions to ensure proper loading of CSS and JS in a synchronized manner?