I'm making this search component that I can just load using javascript and have it work wherever I load it. The idea is that it does an AJAX-search, so I don't want to code that up every time I put one on the page.
So maybe on pages that I want to put it on that would look like this:
var searchBox = new Search(inputBox);
Ideally, I wouldn't really want to have to link a style sheet everytime I do this. I'm just wondering if performance takes a big hit if I just create tags and add attributes like this:
$('<div></div>').css({
'background-color': #002323, etc.
});
I feel like its only slightly more verbose, but it will be much easier to manage and use.
Or do you know a better way of doing this?
Maybe this question is brushing the surface of a bigger problem, which is about making CSS object-oriented. I don't want it messing up other things on the page if there are css attributes with the same name. Everything else I do is object-oriented. Are there any CSS solutions or methodologies for this?
Two things come into mind:
If you ever want to change the style, you will have to do it in javascript, possibly at several places.
Obviously, applying styles one by one instead of just adding a class is slower.
CSS was designed to make your life easier and honestly I think it wouldn't be very wise to not to use it, unless you have some javascript style framework that does a better job.
It seems to me that it rather depends on how much CSS you need to apply to this search component, and whether you need to be able to skin it for different sites. Assuming your javascript is all held in one external file, is it a big problem to create a basic CSS file to go with it, and use the script to dynamically insert a <link> to the CSS file above other <link> elements in the document?
That way you can reuse and skin it very easily, overriding the styles set in the default CSS for any particular site just by adding the appropriate selectors to that site's stylesheet. If you set them all with jQuery, it'll be much harder to change the skin.
The main problems of your search component are obstrusive JS and probably non-accessible tool (except if you took the ARIA road).
The one you're talking about is secondary.
You should use carefully named classes, I wonder what can be easier to manage than a class="warning" (background-color: #FE0114; ? no way)
Related
Is it better from performance standpoint / a more efficient use of memory to have the CSS be created with the dynamically generated HTML elements, or to have the classes predefined in a CSS file waiting to be used?
I could imagine that having CSS sitting waiting to be used could make the CSS file unnecessarily big, whereas using JS to create the CSS could be a less efficient use of memory and processing power.
Would love to hear others' thoughts on it.
I vote for using css classes in separate file :
To separate the display from the processing or the traitement
To be able to manage any changes in the future
Having the possibility to make your CSS dynamic with CSS Custom Properties
Possibility to use css Modules
Take all css advantage
Personally, I prefer having things separate, since it's easier to find/read/update later one. Having a bunch of CSS styles mixed in with JS could make it hard to read and maintain in the long run.
I also wouldn't worry about optimization until you feel that your code is taking a while to load.
Defined in a css file, is a good practice.
If you need to update the css after generating html, Then it will be a good to define in css classes.
I've made some code (tool? framework? Not sure what to call it) that is intended to make it possible to style CSS with Javascript but not jump when reloading or changing pages (so for use in traditional multi-page sites... not sure the conventional term for that). I'm no web expert so am unsure if it's worth developing this further or if there's better solutions to what I'm trying to solve (more than likely).
The basic structure is
A. Under certain client-side conditions (e.g. browser resolution, but could be anything, like a certain user using the site), CSS is generated by client-side JS, written to a file on the server under the appropriate heading relative to scenario (e.g., 1024x768.css, 102400x76800.css).
B. The server code checks (via cookies) if client-side condition is met, checks if css file pertaining to condition exists, uses it, otherwise generates it (A.)
Potential uses
You inherit a legacy site or clients insist on a certain template (Wordpress theme), with predetermined HTML structure, such that it's difficult to achieve a custom look just modifying the CSS. It might be much quicker to make calculations and adjustments with Javascript than refactor the HTML or figure out the solution in CSS (time permitting the ideal solutions, arguably). On the other hand, you don't want the style to jump every time you load the page since that looks tacky.
Edit: example of the above
As noted below in the comments, I can't think of a great example off the top of the ol' noggin. Right now my test is modifying a navigation menu of the type <div class="menu"><ul><li><a>Section 1</a></li><li><a>Section n</a></li></ul></div> such that the <a>'s have just enough padding on both sides that the menu <div> fully fills up the width of the browser.
I imagine there's a conventional solution to this, so if you're feeling in the mood, please let me know.
You want particularly complicated sizing, positioning based on complex calculations (dependent on screen size, or not), but, again don't want things jumping around.
Edit: example of the above
Positioning elements in a spiral pattern (say this kind) with diminishing size. This seems to be nontrivial in CSS, perhaps done by calculating the positions beforehand and placing with absolute positioning. But then there's the problem of having everything scale depending on screen resolution.
Alternately Javascript could calculate positions and sizes dynamically. Of course writing the method to correspond to the mathematical spiral function would be a challenge (though an interesting one).
There could be other solutions like using .svg, but if written generically it would be possible to position according to other mathematical functions (e.g., sine wave), or complex ratios (golden mean) fairly easily.
You want a site where the user can customize the look (reposition or even resize elements) and you want the customization to automatically get remembered and generated in the server-side code (perhaps even without a login). I'm sure this is facilitated by many frameworks, but this kind of divests the process from a specific framework.
I was wondering if other folks had thoughts on whether:
A. There's a better solution to all this I've missed.
B. The system I described of pushing CSS from JS to be written on server sounds sound, or if the same thing could be achieved another way entirely client-side.
C. And I guess since it's not a specific technical question whether this is the right place to ask this question, and if not, where I should.
Like I said, I'm no expert, so would greatly appreciate any feedback or other things that might help me to learn.
Thanks
Many people today use Google Closure Compiler to actually "compile" their JavaScript code. The advanced mode enables it to rewrite JS to better, faster and smaller JS-code that functions the same way as the original input.
Are there any good compilers out there for HTML/CSS? It could for example compress the CSS classes like a JS-compresser does. It could remove any divs (display: none;) that no JavaScript actually displays (display: block;). It could remove whitespaces. It could combine small images into sprites. It could combine files that are included on all pages into one file.
The list just goes on and on. Do you know about any good tools for this job? (Even if it only can compress CSS classes etc.)
Concatenate your css files and you made most of the work : the cost is mostly related to the number of requests.
But for removing useless rules, there is no point in using a tool : needing one would mean you don't really understand which ones are needed and why. In other words your code is a mess you must fix because at this point it may only grow explosively.
That's the same for sprites and other optimizations : only by knowing the use flow of the application, if people come back and have some images cached, or only the ones of the main page, etc. can you know what strategy to use, even if it's almost always useful to merge all your small images of one page in a big one.
No actual compilers as such that I know of, but there are tools to help you create clean html and css.
For css there is, for example, less which is a good tool for generating nice clean cross-browser markup but you have to use it from the get-go. Similarly for html, there are a few markup frameworks that can simplify generation of clean html. markdown is one such that is quite popular.
I imagined this would be super-simple, but it is eluding me so far. I would like to know how I can implement a timer that counts down to a specific date and can be styled with CSS.
Specifically, I have designed a background image/container and want to style the numbers so they are correctly positioned, sized, coloured and in the correct font.
There are a raft of JS and jQuery countdown timers, but none I have found output in a manner which is easy to target with CSS. Modifying the output strings (i.e. including div tags) only seems to break them, although my JS knowledge is not great enough to understand why (a guess, is that the scripts seem to target a certain div class and 'inject' the appropriate code. Perhaps introducing new divs screws this up?)
I guess my question would have to be... 'what is the easiest way to implement a countdown to a specific date, which can be styled with CSS?', although if you know of an existing plug in that does this, I will love you forever!
This is a very useful plugin for countdowns ... everything is written within a div and span's so you can easily style it with CSS - you could use images if you reallu needed to
http://keith-wood.name/countdown.html
I've used this: http://www.littlewebthings.com/projects/countdown/example/
And I can say it's awesome.
Unfortunately it's not in pure CSS, there are images, and the switch is not smooth.
But you can always learn how to make a beautiful countdown like that by studying how it works.
Here you can download the source code: http://www.littlewebthings.com/projects/countdown/downloads/lwtCountdown-php.zip
Hope it helps.
I'm working on a large JavaScript-heavy app. Several pieces of JavaScript have some related CSS rules. Our current practice is for each JavaScript file to have an optional related CSS file, like so:
MyComponent.js // Adds CSS class "my-comp" to div
MyComponent.css // Defines .my-comp { color: green }
This way I know that all CSS related to MyComponent.js will be in MyComponent.css.
But the thing is, I all too often have very little CSS in those files. And all too often I feel that it's too much effort to create a whole file to just contain few lines of CSS - it would be easier to just hardcode the styles inside JavaScript. But this would be the path to the dark side...
Lately I've been thinking of embedding the CSS directly inside JavaScript - so it could still be extracted in the build process and merged into one large CSS file. This way I wouldn't have to create a new file for every little CSS-piece. Additionally when I move/rename/delete the JavaScript file I don't have to additionally move/rename/delete the CSS file.
But how to embed CSS inside JavaScript? In most other languages I would just use string, but JavaScript has some issues with multiline strings. The following looks IMHO quite ugly:
Page.addCSS("\
.my-comp > p {\
font-weight: bold;\
color: green;\
}\
");
What other practices have you for keeping your JavaScript and CSS in sync?
My perspective on CSS files is that they describe rules that define the theme of an application. Best practices generally state that content, presentation, and behavior should be kept separate so that it is relatively easy to change that theme. By having multiple CSS files, this becomes slightly more difficult, as a designer would have more files to deal with.
Additionally, CSS (Cascading StyleSheets) rules are affected by their position in the CSS document. By having multiple CSS files with different rules in each, it may become more difficult to prioritize which rules take precedence.
Finally, if you want to find out what CSS selector in your JS file matches what CSS file, try using a cool search tool, like grep, if you're on linux. If you're using a good IDE, you can also use it to quickly search for the rules, then you can just jump to the line number. I really see no advantage in keeping the CSS rules in different files; it will only complicate matters.
Additionally, I would advise against the idea of putting the CSS inline. By doing this, you will inevitably make it more difficult for your web designer to quickly and easily swap out the styles. The whole point of external CSS is so your web designer can change the theme or provide multiple themes for different users. If you embed the CSS in the JavaScript or HTML, you've then tightly coupled the content, behavior, and presentation.
Best practices generally suggest keeping content, behavior, and presentation separate for this very purpose.
Having one CSS file per JS file seems a good thing for me. It's clean, and easy to understand and to maintain. The only problem would be to have dozens of CSS files on every page, but I suppose you combine those files to one big file, so this problem does not exist in your case.
How to embed CSS in JavaScript? It depends on the environment you have, and how the build process is done. The easiest thing is to have a large comment at the beginning of every JavaScript file, something like this:
// <...>Your copyright notice here</...>
// <css>
/*
body{color:red;}
div{border:solid 10px lime;}
// ... other ugly styles.
*/
// </css>
Then during the build, you have to search for <css>...</css> blocks and extract the CSS by trimming the /* and */.
Of course, it creates a problem: if you are using an IDE with auto-completion, embedding CSS into a JavaScript file will make it impossible to use auto-completion in this case.
My preferred method is to keep all the CSS files separate and then have a build process that compiles them into a larger CSS file on deployment.
I would avoid merging your JS with your CSS. It may sound like a cleaner solution from the file-level, I think it'll get messy fast. That, and you'll lose the highlighting and syntax assistance your editor gives you.
Check out Csster. I wrote it to solve just this problem.
You embed your CSS rules directly in your Javascript, using Javascript object literal syntax. It's no uglier than raw CSS.
Csster.style({
h1: {
fontSize: 18,
color: 'red'
}
});
The rules are inserted into the DOM on the client side. This architecture simplifies your build process and reduces client requests.
You can use it like you describe, but Csster also provides a couple other niceties:
nesting to DRY up stylesheets
color functions like darken and saturate
built-in macros for common CSS idioms like clearfix, rounded corners, drop shadows.
extension points for custom behavior or cross-browser support
It's well tested and I've used it on quite a few projects. It is independent of jQuery, but plays well with it.
I'd love to have more people use it and provide feedback.