-
-
Notifications
You must be signed in to change notification settings - Fork 365
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
making this a little more clear - dynamically applying stylesheet to document #194
Comments
We can dynamically add stylesheets to the document like this: <html>
<head>
<link rel="stylesheet" href="stylesheet.css" type="text/css" />
</head>
<body>
</html> $(document).ready(function () {
$("a").click(function () {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
}); but TMK this will do an AJAX request to look for the file on the server, not in JavaScript runtime |
Perhaps this is the answer: http://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript var sheet = document.createElement('style')
sheet.innerHTML = "div {border: 2px solid black; background-color: blue;}";
document.body.appendChild(sheet); This should be in your examples, no? It took me an hour to determine that it was just a matter of appending a string like that. Bah humbug. |
This lib loads and inserts the CSS into the page automatically.... It doesn't go into "JS memory" See line 129 |
you mean this line: var link = document.createElement('link'); //129? are you aware that you can do this: var sheet = document.createElement('style'); //1
sheet.innerHTML = "div {border: 2px solid black; background-color: blue;}"; //2
document.body.appendChild(sheet); //3 as per 'link' uses AJAX behind the scenes, so it won't work with the r.js optimizer if you don't see what I am saying I can try to explain more, but basically what I am suggesting is to use the above 3 lines of JS to add stylesheets to the page without having to re-retrieve the stylesheet from the server. hope it makes sense |
In development, it always retrieves from the server, the same as it does with your JS. When optimized, the CSS is included in the JS file (like with any other dependency), along with a helper script that will insert the CSS into a style tag. So it actually does everything you talk about already. |
And link doesn't use ajax behind the scenes. It's a plain old request, same as adding an image. |
this all looks very promising, and I am very familiar with RequireJS at this point. But what's not clear to me about your lib is how to actually dynamically add the stylesheet once it's JS memory on the front-end. So ok, say I have this:
The text was updated successfully, but these errors were encountered: