Import stylesheet dynamically with dojo
what is the best (the most elegant :) way to import css stylesheet from javascript.
Maybe dojo has some module similar to dojo.开发者_运维知识库require ?
Thanks for help.
You can simply add the <link>
element to the page. After added, it will load the css.
var element = document.createElement('link');
element.href = 'someCssFile.css';
element.rel = 'stylesheet';
element.type = 'text/css';
document.body.appendChild(element);
Dojo has some DOM sugar, if you like:
dojo.create("link", {href:'someCssFile.css', type:'text/css', rel:'stylesheet'}, document.getElementsByTagName('head')[0])
Long ago, Dojo's loader used to handle stylesheets and automatically pull in CSS for modules or widgets (effectively an abstraction to trigger something like the above). There were various browser quirks to deal with back then for loading style sheets. It turned out to have a lot of performance problems, so as of Dojo 1.0, style sheets are loaded directly on the page.
Oops, found this very late however:
Get all stylesheets:
require([ /* "dojo/something", */ "dojox/html/styles"],
function( /* something, */ stylesheet ){
console.log( stylesheet.getStyleSheets() );
}
)
Get a special stylesheet via href or title tag:
http://dojotoolkit.org/api/dojox/html/styles, see getStyleSheet
You asked especially for dojo and so you might also want to read more about dojox.html.styles : http://www.sitepen.com/blog/2009/03/13/dynamic-stylesheets-part-1/
精彩评论