Because I like keeping all source code in one file (per class), I decided to add all style and CSS using JQuery objects, i.e:
jquery : $('<div/>',
{
id:'Object',
css:{
height:'100%',
width:'69%',
color:'white',
fontWeight:'bold',
textAlign:'center',
backgroundColor:'#02297f',
marginLeft:'.5%',
'float':'left',
overflow:'auto',
borderRadius:'5px'
},
html : 'My JQuery Object'
}),
Now I know there is probably going to be some sort of performance impact, but my question is how much? Does anyone else do it this way? Am I overlooking a potential problem?
I like it this way because I can just use objects rather than having to cross examine a stylesheet and it keeps it better organized.
EDIT: This is for a Javascript application, not a web page. So disabling the Javascript will kill the webpage anyway.
There is certainly a performance impact. The script is only run when all the page is loaded, so it will give you problems when the page is first displayed.
Apart from that, you got no styling at all when you run a browser where javascript is disabled.
But most of all, it is a Bad Idea. CSS is for styling, for the looks of your page. HTML is for structure, and Javascript is for logic, interactivity. I think you shouldn't use the .css method at all. If you need to toggle styles in Javascript, use classes instead, which can then be styled using style sheets.
But this method of yours takes it a step further even. I think it's even worse than putting all the css in inline style attributes. I hope you are just asking this question to see how people respond. It must not be serious. :s
Your are doing it wrong.
CSS must stay in *.css files and Javascript in the *.js files.
There is this thing known as 3 layers of Web:
content ( HTML )
presentation ( CSS )
behavior ( JS )
First of all, yes, if you use JS to generate html and style it, this would have a huge impact on performance. But even ignoring it : you would make the code virtually unmaintainable.
If you want to have better organized stylesheets, then invest some time in expanding your knowledge in CSS, and looks at practices behind OOCSS.
Thats a TERRIBLE IDEA! Use instead http://xcss.antpaw.org/
I agree with the way you're doing it. I essentially use it myself. I am developing a html5 game and in that context what you are doing makes sense. In games, user events and system events constantly change the screen. You can only realistically deal with this via just-in-time styling. So using .css() is a great way to do this. I think in a game that sprites are so distinct that they require their own style object.
Related
I’ve been looking into some of the Squarespace template design resources to better understand an existing template.. This got me looking at Less, and I’m not sure I’m seeing where it fits in. The documentation mentions Node.js and compiling Less, it seems like it’s basically JavaScript like stuff in CSS.
I’m not sure I see what Less is adding that couldn’t also be accomplished with some form of JavaScript and since it seems like it needs JavaScript anyways. Not sure if I’m just missing the point of Less or there’s something it does that couldn’t be done in JavaScript that I’m not seeing.
Everything Less does can be accomplished with Javascript but it wouldn't be practical using it to manipulate the stylesheet in every instance.
In Less, something like this:
#link-color: #428bca;
a {
color: #link-color;
}
Would look like this in plain JS:
const linkColor = '#428bca';
document.getElementsByTagName('a').forEach(link => {
link.style.color = linkColor;
});
You're giving the browser far more work interpreting Javascript and setting a style than serving it a generated CSS file that Less outputs.
It's also a separation of concern. Typically you'll use HTML for layout, CSS for styling and Javascript for interaction and picking up pieces where CSS may not be enough.
For best performance you'll use those in that order as needed.
Less must first be converted to CSS so browsers can interpret it and does not require Javascript to work. Seeing that including a Less file in your template on Squarespace should get converted automatically, you're giving each user no additional overhead in drawing styles on the page, speeding the site up.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This is more of a general practice question that a problem specific one but I'll give an example of what I mean. There are a lot of things you can control with CSS that you can also do with Javascript, but is one better to lean on than the other?
Example:
I have four buttons in a nav that are given a class of "selected" when the section they're associated with is in view. So I could either write a CSS statement for each button (or have Sass do it for me with a mixin)
#home-butt.selected{
background-image: url(images/home-up.png);}
#about-butt.selected{
background-image: url(images/about-up.png);}
#work-butt.selected{
background-image: url(images/work-up.png);}
#contact-butt.selected{
background-image: url(images/contact-up.png);}
Orrr I could write something in javascript to do the same thing. (*I gave the images a title attribute that matched the image name so it could pull from there).
title = $(this).attr('title');
$(this).find('img').css("background-image",
"url(" + 'images/' + (title) + '-up.png' + ")");
So my question is which is better to use? Is it the javascript because it's less lines of code? Or the CSS incase javascript is disabled? Or is this a very situational question where there isn't always a right or wrong answer?
Opinions and rebuttals are welcome!
To answer your question about "is one better to lean on than the other?"
Keep in mind, that CSS has a specific purpose. To apply the look to your application. JavaScript on the otherhand, is mostly the feel of your app. Always prefer CSS over JavaScript when editing styles.
The only time that you ever should modify styles using JavaScript is when you have a dynamic application, and need to change styles based on some unknown variable. Even then, a lot can be achieved with just using CSS.
Also keep in mind that you are using jQuery. think about jQuery's constructor. it is a CSS selector.
With the concept of CSS pseudo-classes introduced, there is very little that you cannot achieve style-wise with CSS.
In many cases where Javascript developing makes what I'm trying to accomplish much more easy and other cases where CSS does that to.
" In the end each "language" has its appropriate place in web development and used wisely can enhance both development and user experience. Learn what those uses are (I recommend experience learning) and apply wisely. In my experience, set in stone rules such as "Never use JS when a CSS solution exists" (paraphrased) are rarely best in the practical world. "
If you are working with layout, use CSS, if your creating the look and feel use CSS, if your doing animations use CSS3
If you attach event handlers or reacting to user input use JavaScript.
Usually you want to use CSS, because it's much faster than javascript. Also there are going to be users with javascript disabled, which aren't going to see your enhanced presentation if it relied on js function.
The usual answer is, use CSS when you can, because it will work with JavaScript disabled, and also because you don't have to deal with issues like waiting for elements being available in the DOM before referencing them.
But sometimes it depends. Keep in mind that:
Depending on the selector or properties you're changing you may have issues with browser compatibility.
If you're changing the image like in your example, you may see it flicker while the new image is loaded. You can avoid that by using a sprite image, or preloading the images with JavaScript.
As a general rule of thumb, I would use CSS for styling and JavaScript only to "make the page alive".
So the best and the most ideal use of JavaScript is to add and remove classes from elements
- classes, which your CSS is depend on.
Loading the jQuery library to perform this simple task is unnecessary and relying on javascript to apply background images to your img tags is unnecessary as well.
If it can be done properly in CSS, and work in all browsers, then it should be done in CSS.
Javascript is for more advanced or complex tasks, which require interaction or animations that CSS can't provide for all browsers (due to cross browser compatibility issues - check out caniuse.com)
In your example, if the .selected attribute is being given dynamically by javascript for instance:
makeSelected(elm)
{
document.getElementById(elm).className='selected';
}
then i would still personally add the styling for .selected in CSS instead of adding the image through javascript.
If you're adding .selected based on the current page you're on and not through javascript then I would recommend using CSS.
I prefer CSS over Script for one main reason Browser compatibility
There are just soooo many times when one script code or the other isn't compatible in one browser or the other (cough or just IE)
With css I haven't had such issues yet (touchwood) and also if there were any issues CSS's won't affect as much as script's which just don't let any other following codes to execute.
Let me provide my opinion.
Personally I don't believe a website should have a lot of "gimmicks" in terms of designing.
BY gimmicks I mean hovering effects, music in the background(absolute no-no) or other "eye-catching details". All of this looks good the first time but subsequently visitors get fed up with this distractions.
Without deviating from the main issue. CSS/JavaScript for styling.
Well they do exist hand in hand. The best example for this would be Bootstrap library. Although I have never used it personally but it seems amazing what can be achieved using CSS and JavaScript.
So, We will need both to design spectacular website. CSS helps in the basic designing and to make the website more responsive we use JavaScript and its derivative libraries like Jquery for all the finer looking stuff
I am developing a large scale HTML5 app, and I really wonder about this issue. I will have a lot of dialog boxes and tabs that will open by user interaction.
I wonder what is the best practice - writing all the dialog boxes and tabs in the HTML document with display:none to all of them, or create these HTML sections on the fly with JS or jQuery every time the user making the relevant interaction.
What is better in terms of performance, ease of development, readability, etc?
Any help will be appreciated.
I'll try to address this question as good as I can.
1 - As I said in the comments, Avoid inline styling.
First and foremost this is because inline styling voilates DRY.
Having to repeat the same thing over and over again for this is very bad for maintenance and for developing since instead of changing code once you have to change it at ~100 places.
2 - Avoiding inline styling is also good for accessibility, some screen readers and search engine crawlers do indexing work and reading work based on css selectors and thusly using inline styling will force them to either ignore or misintrepret things.
3 - When working as developers it's easy to do inline styling "just for the fun" but what you're actually doing is mixing concerns. HTML is the content and CSS is the design.
Mixing these two usually leads to headaches and making my job as a developer that comes after you a pain in the effin ass since I have no idea what's styled and how.
Now, onto performance.
When you use inline styles, what you're telling the browser is basically "hey, for every page page view apply these styles to all of these elements." Now, this just became really apparent why this is bad.
You have no ability to cache and store your css and basically forces the browser to rerender your styles every time. Using an external CSS file will actually help you speed up your site since the browser caches it.
That was that for the css part.
The javascript you had asked about.
As I said, hide things with css and show with javascript. Now why do you want to do this instead of pulling everything in?
Well, you can do both. If you're only a webbrowser experience then you can do either, it doesn't matter. I myself prefer to have stuff in the DOM because it relates to content and if you're a large app having dozens of dozens of ajax calls will only make it harder for maintenance. I believe if you have to ajax stuff in make sure it counts and is logical and not just for the kicks (I think this applies if only you have jQuery and plain javascript at your disposal).
If you're working with backbone.js, for example, it's based on views and introduces some form of "MVC" into your frontend enabling you to have views with subviews that can pull content in from the server.
Hope that helps a bit with making a decision! :)
I would say it depends on how many tabs your application has and how big these are.
Big content inside the tabs mean that the application will take long to load when started and consume much ram. If this is the case, I suppose to load them as needed.
Small content inside the tabs will load fast, so load everything at once to increase performance when the tabs are clicked.
Don't forget to run some tests on older computers with a slow internet connection to see how your application behaves. Not everyone has the newest and fastest hardware.
I'm trying to improve a websites rendering speed.
Both CSS and JS files mostly reference elements like this:
Javascript:
$('.some_element').doSth()
CSS:
.some_element { /* do something */ }
Just curious - is this the optimal way of referencing elements in terms of javascript parsing and website rendering? Wouldn't it be better to do something like div.some_element?
Thanks for some infos!
If speed is a priority you might want to switch to vanilla javascript as much as you can. Native javascript is faster than jQuery.
If you want to keep your jQuery selector use parent context to make the search for the element more efficient. Example $('#parent').find(child)
You can find more tips on javascript an jquery optimization on the web:
http://engineeredweb.com/blog/10/12/3-tips-make-your-jquery-selectors-faster/
div.some_element will be different than .some_element, if you don't just have divs that use the some_element class.
Maybe compare render times using Chrome's built-in developer tools (or an alternative) to see if it helps you, but I doubt it'll be significant.
The fastest way to find a single element is usually with an id, not a class:
document.getElementById("whatever")
If you have to use jQuery (which is not as fast as plain javascript), then you would use:
$("#whatever")
If speed is really important, you can resolve the DOM element once when the page loads and just save the direct DOM reference so you don't have to find it when your code actually executes later.
As with all questions of performance, the only real way to answer a performance question is to benchmark a couple of implementation options and actually test which is faster.
I'm currently learning jQuery by reading jQuery in Action.
The book discusses separation of concerns by using 'Unobtrusive JavaScript.' I grok that keeping behavior specified by JavaScript out of the <body> tree is good form and goes a long way toward maintainability.
However, the benefits of using that approach seems to be negated when looking at dynamic HTML generation with jQuery, such as this example:
$('<img>',
{
src: 'images/little.bear.png',
alt: 'Little Bear',
title:'I woof in your general direction',
click: function(){
alert($(this).attr('title'));
}
})
.css({
cursor: 'pointer',
border: '1px solid black',
padding: '12px 12px 20px 12px',
backgroundColor: 'white'
})
.appendTo('body');
from jQuery in Action, 2nd Edition
Here, we're mixing structure (the new <img> element), style (with the call to css()), and behavior (by setting the click attribute value.) So, we no longer have separation of concerns, even though this block is placed in the <head> of the document.
Is my understanding correct? What are best practices to mitigate this? Is it common to refer to external .css and .js resources when doing this type of HTML generation in practice?
Best practice is to use a templating engine (like Mustache.js or jQuery's built in templating engine) and classes, via .addClass.
But at the end, you just can't completely separate the V from the C (View from Controller - MVC), especially in html.
I think the best practice would be to use classes in jQuery and keep your css in a separate style sheet.
EDIT:
I would also add that learning straight from the horse's mouth works for me. I use http://api.jquery.com/ for almost everything I really need to understand jQuery related.
Your missing the point here.
With unobstrusive Javascript the main aim is that in case if Javascript fails to load or execute, how will your application respond? That's the key thing as people have Javascript disabled in many pages, so will your application show any content and respond in a normal fashion or would just go dead?
You can't really separate the View from the Controller but unobstrusive Javascript helps in that direction. But the real benefit is resilience.
Also if you want good abstraction, use KnockoutJS. I cannot really emphasize any less and I can't imagine creating huge websites with great client-side code without a similar library.
The big picture of separating HTML, CSS and JS is that you want your site to be usable (and navigable) if CSS and JS are not available.
For example, if your site depends on JS to load content -- without any kind of "fallback" -- it's broken for anyone who doesn't have JS enabled.
It's perfectly possible to have a full-featured site that uses all the benefits of CSS and JS, but getting them to work together so that the site fails gracefully if your CSS or JS isn't loaded, is a goal worth achieving.
Speaking from my experience with jQuery separation is the best way to keep maintainable code and also keep design, content and functionality separate.
Markup
Refering to your example - in most cases markup comes with your html file or is requested by ajax calls.
CSS
jQuery's css functionalities are mostly used in case of onpage manipulation, the original css properties still come via css files.
Events
Usually you maintain a 'bind-section' within your script, where you define all your bind/live events:
$( '.clickable' ).live('click', function(){
// do something if clicked ...
});