Dynamically generated css - javascript

I am considering replacing a number of static css files with style tags dynamically generated from JavaScript. My purpose is not to build a stylesheet for the whole document, but rather to use it for plugins that get added to the page, like tabs, slideshows, etc. The stylesheets I currently deal with have 10 to 20 lines.
I see several benefits:
load only a js file instead of both js and css
ability to define theming on the fly (e.g. enter colors as variables)
ability to define selectors on the fly (e.g. namespaced class names)
add browser specific styles
What would be the drawbacks of this approach? Could you recommend any good references on this topic?
I did some research and found the following tools:
less - but still requires to load a separate stylesheet
DiceJS (apparently a new library)

Less is absolutely awesome, I don't think you should try to generate css with a custom library in javascript. It's a good idea to keep your javascript as separate as possible from your css.
We use certain element class="" attributes to trigger javascript logic, but they never overlap with classes used in our less styles. (we use different casing rules for both to prevent overlap from happening).
There's also not that much benefit to dynamically load parts of your css. We have the less.js javascript running during development, but we run the 'lessc' compiler for production so we always have 1 stylesheet (and also compressing it with YUI Compressor).
Unless the total css is absolutely humongous, we prefer to load in 1 big css file at the first hit, and afterwards have the file cached.
Making sure all your css is loaded at all times (and not just parts) also helps you enforce that there are no conflicting rules. This will really benefit you if you ever must to refactoring and parts of your application move to other urls (where all of a sudden overlap becomes visible).
So I'd suggest, rather than trying to solve your issue by dynamically generating the styles you need, you may just need better organization for your css.
If you're looking for a great example of effective use of less, check out Twitter Bootstrap

Another benefit would be that each additional asset that is loaded in the page slows down the overall page load because a browser is typically only loading 4 assets simultaneously at a given time.
However, doing all of that combining on page load is likely to cause the page to slow down just as much from the processing alone... depending on how many things it needs to iterate through to make up the final css block.
In terms of performance, it seems very unlikely to me that javascript is going to elegantly / efficiently replace the styles that would've been included in a combined css file.
The other thing is that in production environments, you also can do another option which is to use a library to pre-generate a set of minified, optimized, (and obfuscated in the case of JS) code and then have 1 js file and 1 css file loaded at the time of page load, which in-turn you'd cache for speed/loading benefits. Boilerplate lib has a script for this i think.
End of the day: energy is neither created nor destroyed -- your optimizations in one place and hurt you elsewhere if you're not careful.

Using JavaScript for CSS sounds a bit messy, in my opinion. As you mention your self, I would instead recommend you to use LESS or SASS or similar. Yes, it would cause one extra resource to be loaded, but I think that is well worth it compared to using JavaScript for styling. In my opinion, it is the wrong tool for the purpose.

Related

Changing inline style vs. changing external stylesheet style using JS

What are the benefits of changing particular bits of style inline in the HTML or changing it from an external stylesheet using Javascript?
For instance, this post explains how one can accomplish changing styles from an external stylesheet. However, the process seems to be much more complicated than changing it inline, and it also refers there may be cross-browser problems. However, the post may be outdated (it is 3 years old, and one of the comments says even then it was 4 years old). Is there another more recent way of doing this?
I ask this because I try to keep my HTML and CSS completely separate.
However, is it maybe simpler, in terms of legibility and performance of the code, to simply specify the styles I want to change inline rather than on an external stylesheet?
Are there any best practices in regard to this matter?
When temporarily accessing or modifying an element's style using Javascript, there is no difference involved in whether that style was defined inline or in css - you will get the style that is applied by precedence and Javascript changes will override any declared style.
However, general best practice is to have a separate stylesheet (or maybe several if you intend to have conditional stylesheets for IE9 and below, or to split up lots of styles into manageable chunks)
This method is less complicated when it comes to debugging and changing styles in real time.
With external stylesheets you can change the entire site in seconds by dropping a new .css file in place. You can't do that with inline styles.
There are no benefits from inline-css except that it will be given more importance.
External css have the benefits of being cached.
However while rendering the below is the order followed.
Inline CSS styles are given more importance than to styles declaredd in <style></style> and styles declared in <style> is given more importance than to styles declared in external css. files.
Inline-css and even <style> is not preferred and is generally bad practice as extra bytes are transmitted over HTTP and they cannot be cached as external css files can be.
Styling using javascript should be just up to adding a class or removing a class or hiding and showing them, to improve the user experience.

Does javascript run after HTML element css display:none executed?

I'm building a responsive site. But on the phones, it takes much time for loading to be done. I think it's because of javascript. On slow speed phones, executing javascript maybe a problem. So if I hide some elements (display: none) which will be handled by javascript, will all scripts for those elements be executed as normal or any way else?
Maybe this is a bad question but someone please explain how javascript works in this case.
Yes, unless you're using the :visible selector, jQuery will still find elements styled with display:none which are in the DOM.
JavaScript can still see those elements.
There are a lot of things that can hurt performance on phones, and there are a lot of things that can be done to help make it better (shallow CSS selectors, events delegation, off-DOM manipulation, restructuring JS to be modular, and lazy-loading it onto a page, .png optimization for images, concatenation and compression of JS/CSS, object pools for memory-management)...
A lot of things to squeeze more performance out of phones...
But "display:none" isn't going to stop JS from seeing or using those elements, and if you're doing a lot of query-selector stuff:
$("#my-div .my-span").each("...");
It's going to keep right on doing it.
Display being set to none on an HTML element does not prevent JavaScript from being executed on it. Otherwise it would be troublesome to show and/hide elements with JavaScript.
To speed up your site, there are a number a techniques that can be used. Many are dependent on your situation. It sounds like you may benefit from late loading the JavaScript, i.e. moving it to the bottom of the body tag. Doing this will allow your page to render prior to loading all of the JavaScript.
Google's PageSpeed may help guide you to other ways of improving your page load time.
https://developers.google.com/speed/docs/insights/about

Is there any problem using JQuery/JavaScript to apply lots of CSS styles?

I want to apply ALL the CSS styles 100% with JQuery/JavaScript
But is is bad idea to do this?
Why would you create that overhead in javascript when straight HTML/CSS is fully capable of handling it? (in fact intended to)
Also, you're adding an unnecessary requirement to the styling of your site: having javascript enabled.
Main reason IMHO: Performance! Native CSS is much faster than JS.
Also worth mentioning:
Doesn't work for users with NoScript etc.
Overhead. Not such a big deal i think. There are more important things to optimize.
If you lazy load stuff, e.g. by using jQuery.load(), you have to reapply your styles to these elements. Not nice :/
Conclusion: CSS is made for styling, JS isn't.
If your visitor has javascript disabled, they'll see an ugly white page without any styling.
I don't see why you would do this, to be honest. It's not user-friendly.
Use a stylesheet.
A lot of people say to apply classes not individual styles.
You will see varying levels of performance degradation across different browsers. It's faster and cleaner to let the application render the styled HTML page because that's what it's optimized to do.
If you're dynamically loading content and already have fade effects/transitions so your content is only revealed after it's styled, you might be ok.
if you are going to do this, only apply styles with jQuery (rather than using javascript) to maintain cross-browser compatibility.
I would recommend against your approach because of the time it will take jQuery to loop through all of your elements and apply styles.
something like $('span').css(...); has to traverse the entire DOM and loop through a collection of elements. $('#title').css(...); does not have to loop through the entire DOM because it immediately knows where to look.
Also, browsers are designed to process stylesheets and render your styled elements very quickly.

Caching of HTML Output

I am pretty sure that I know the answer to this already, but I am interested to see if anyone has other ideas. We are working on a website to include a major redesign with mega menus. One of my top things in a redesign is to reduce the page download time as much as is possible. All my images, css and javascript are cached and that's good. However, the part that I am trying to work through is the html coding for the menu, and if there is a way to locally cache that within reason.
As a side note, I like to do things as pure CSS as possible (for SEO), and so that would include outputting the mega menus directly onto the HTML page. But at the same time, I know that if it takes a number of seconds for the page to download the html content at the top, well, then, we are probably going to be running some customers off there too. Maybe the best then would be to have JavaScript output the menus, but then you run into the couple of customers that don't have Javascript enabled.
Right now the pages are about 30K for the menus, and I anticipate that doubling and maybe more when we do the redesign.
Do you have some thoughts for this issue? What would you see as the best way to tackle this?
Thank you!!
JMax
Honestly, 30K for an element is nothing in this day and age, with high-speed connections common and browsers effectively caching as necessary. People don't leave because of a second or two. It's when you have Flash movies that preload or crazy auto-starting videos that people get annoyed in a hurry.
I've got a similar application with a menu that's likely double that right now...let me add, it's not by choice, it's something I inherited and have to maintain for the time being. The menu is output simply in an unordered list and then I use Superfish and CSS to do the styling as necessary. There's an initial hit, but after that, caching kicks in and we're good to go. Even as crazy as it is, the load isn't prohibitive. Navigating it, however, is a mess. I'd strongly recommend against confusing the heck out of your user with so many choices, especially on a mega menu that can be a UI hurdle for disabled and older users. When you boil it down, the whole basis behind the "Web 2.0 movement" (I hate that term) is to minimize or cloak complexity.
If you're REALLY concerned about performance, start off with what you're loading. Limit your Javascript by combining files, especially those small Jquery files that tend to stack up. HTTP requests can severely impact a site, especially since they monopolize the loads initially. Similarly, combine small CSS files and optimize the rest via an online tool To reduce image loads, create sprites for your graphics so you're loading one file instead of many. Here's a tut on Sprites and a simple google search will give you dozens of sites that will build the sprite and css automatically. Load anything you can from CDN, such as Jquery, Prototype, etc (hopefully only one framework per site, because two or more is unnecessary)
If you're still out of hand, look at your graphics one more time. Could you take advantage of pure CSS or image repeating via CSS to reduce loads further? Have you optimized all the graphics? Could you tweak the design to take advantage of those tricks?
After all that, if you simply can't change the menu to be more friendly, start investigating options. However, I suspect you'll find better gains in the first couple of steps than you would from taking extreme measures on the menu.
You could either set HTTP caching for a javascript code file that generates the menu, or use ajax to insert a pre-generated HTML menu from another file (again with a long expiry date set on cache).
Both those solutions require javascript through. I can't think of another way to remove the menus from the HTTP traffic apart from an IFRAME (yuck).
30k is massive for plain HTML though - do you REALLY need such a huge navigation structure?

Replacing CSS with JavaScript

I'm relatively new to client-side programming coming from the PHP/MySQL environment. I understand the roles both CSS and JavaScript can play in the browser environment, however, it appears CSS is irreversibly stagnant without JavaScript. I by no means want to create a debate but this is what the situation looks like to me, the "novice." So why not just use only JavaScript to set element attributes/properties? And if so, is this a common practice? (I'm sure CSS is much faster...)
Some general points:
CPU Cost
Running Javascript to apply styles to individual elements will incredibly slow. Javascript is synchronous, so it'll have to update one style at a time. Plus, as mentioned elsewhere, traversing the DOM is computationally expensive. More so if you're applying styles since you're forcing the browser to re-render the site each time you apply a change.
Brain Cost
It's also mentally expensive to try to write and maintain styles in Javascript. It's a functional language never intended to contains the rules of layouts. CSS is just a lot easier to read.
They Cascade!
CSS stands for Cascading Style Sheets. One of the great benefits styles can inherit properties from eachother. Consider the following:
a.nav { font-weight: bold; }
Now all your links with a class of "nav" are bold. But should you wish to further modify a link you'll still be able to:
li a.nav { color: red; }
Now all your a.nav links contained within a list item will be red and bold. It's possible to do this is javascript, but you'd have to force it and maintenance would be horrible.
If you use Javascript for styles your coworkers will beat you to death!
I think this one kind of speaks for itself
Css is for page layout and style.
Javascript is for behavior.
Even if it is possible to completely replace css with javascript, it's not considered standard practice and would be frowned upon severely by most web developers.
Good web development always assumes that a client may have javascript turned off and will provide for a graceful default setting. Replacing css with javascript may make this impossible.
It is far from a common practice, in fact it would probably be viewed as a bad practice!
CSS is used to set the styles of the page and it is rendered when the page loads. Javascript comes into play after the page loads and can manipulate the existing styles and page.
If you were to put it into all JS it would be hugely inefficient! DOM manipulation gets expensive if you do it a lot in JS, and doing all styles in javascript instead of CSS would be lots of manipulation. The load on the client would be ridiculous and there would probably be a noticeable lag in the client as it tried to make all those changes. Plus what happens if a client has javascript disabled? There goes your entire site's look and feel.
Think of CSS as defining how the page looks and should be rendered, and then think of JS as changing that page after it's done rendering. You shouldn't push anything into a javascript that you can do with a simple CSS style up-front.
The real problems with changing out your CSS for javascript would be maintainability and performance. CSS makes it very simple to find a single elements styling, and change it, without effecting the rest of your page. Javascript would become cumbersome at best for even a simple page, and completely unmanageable for a more complex page.
On the performance side, any time javascript is executing, your page will "freeze". Considering a page with 1000 elements needing laid out, your execution time might easily grow to a minute or more, depending on the complexity of the layout. CSS would handle this natively, and without any "freezing" of your browser. This would cause your page to be unusable for the first bit of time that a person visits, and (according to statistics) you only have 10 seconds to capture the attention of your viewer before they become disinterested in your page and leave, meaning you drive away all your new visitors.
The only time you should use JavaScript for setting style properties is when you need to change the style at runtime. You should always use CSS for styling where possible because:
CSS tends to be implemented a lot more consistently across browsers than JS
A user may have JS disabled
The "code" to do styling in CSS is a lot terser, and easier to read/write than the equivalent JS code

Categories

Resources