Tutorial :Downsides with applying all css within javascript(jquery)?


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)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »