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

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

Related

Javascript animation fallback

I'm using the following script for entrance animations in a project: www.justinaguilar.com/animations/
My concern is that this entrance animations rely on "visibility: hidden" property in CSS in order to work. I'm afraid that if JavaScript or CSS aren't available or don't work properly on the user end, the content wont be displayed at all.
Should I be concerned about this?
Is there a better alternative or some fallback plan I could implement?
Thanks.
I think about that in this way.
If this is your only problem about JS disabled, or if you have just a little JS in your page, maybe it is worth find a way to fix it (probably turn the animations off and making the site a little "uglier"). In that way, you're providing access for everyone (and that was a good concept).
But, personally, I've never cared about that. All websites that I've developed contains a lot of JS (with Ajax calls, for instance), it'd imply in a lot of (unnecessary, in my opinion) work for making them functional without JS.
Searching about it, I've read this question. In 2010, 0.25% of the users in Brazil (country where I live) had JS disabled in their browsers. This number should be even less these days. And honestly, I have better things to do with my time instead of caring about these people.
In short terms, my opinion is: if you just use JS a little (or if it's really necessary make this site work without JS), fix it. In all other cases, forget about that and focus on what really matters.
EDIT:
If you wanna guarantee the content will be displayed, you can hide the element via JS. In this way, the element will only be hidden when CSS and JS are on.
<div class="element-to-hide" style="visibility:visible;"></div>
<style type="text/css">
.hide {
visibility: hidden;
}
</style>
<script>
$('.element-to-hide').addClass('hide');
</script>

is positioning with javascript a good practice

I've just learned javascript and jquery a few weeks ago, since then I always use it to position all my divs and stuff in the screen by knowing the size of the screen and the window which I find extremely useful, but now I don't know if is this a good practice, cause it makes my web-pages fully dependant on jquery which I don't know if it may cause some troubles with different browsers.
I would really like to find answers like "Sure is a good practice, use all the scripts you want" cause I'm really loving this javascript stuff but well just tell what you think.
Use JavaScript for behaviors and CSS for styling.
Styling with JavaScript is slower and difficult for another developer/designer to figure out what you did.
Also if you use Firebug or Chrome Web Inspector you can not see where your styling is coming from.
Optionally set classes from JavaScript and not specific styling. You can transition between classes to create a nice effect. But at least your colleague can see where the styles are defined and change it.
I'm sorry, but I'm going to burst your bubble, somewhat.
It's somewhat OK to do it - as long as the page looks OK if you disable Javascript, as well. I would say it should look even better than OK. I would also say that you should only do that if the functionality of your site really demands Javascript, as well.
Keep in mind that a certain percentage of users will have Javascript disabled. I've seen sites that look horrible this way (I use NoScript on Firefox, and selectively enable Javascript as I browser), and a couple where nothing at all appears without JS enabled.
Bad.
As Darin notes, you can (and should!) use CSS for positioning and styling. That is what it was made for! Feel free to enhance the page with Javascript, but keep in mind what I say above!
You could use CSS for positioning and styling of elements. That's what it was designed for.
It's okay to use it for positioning in some cases, but using CSS is the better practice whenever applicable.
Well, In my opinion you should avoid it as often as possible. But I know sometime you don't have the choice.
And yea you can make great web apps using scripts.
It depends what you're positioning.
CSS should be your first choice for positioning standard, run-of-the-mill sections and elements of a webpage. To opt for JavaScript in these cases suggests a lack of understanding of CSS.
Likewise if you find yourself using JS to position things for different devices. Again, CSS has evolved; media queries came along for that. Rule: always exhaust CSS possibilities first.
That said, it would be oversimplification to suggest that JavaScript never be used for positioning. All of us, rightly or wrongly, have resorted (and it is just that, resorting) to JS in order to get things to look right cross-browser, particularly where support for older IEs is concerned.
But by far the biggest use case for JS positioning is for modern web aps and games. If you're building a game with random asteroids dotted around, JS is absolutely the choice for that, since the positions are based on calculation and computation.
Finally, bear in mind that when you position in JS, you are of course still using CSS. JS doesn't have its own, concurrent styling/positioning system - it simply sets CSS properties. It is simply able to do so more dynamically and conditionally than flat CSS.
It is almost certainly bad practise. Use CSS for styling - JavaScript to do this is slower, more work, and more prone to breaking.
If you're positioning everything absolutely (fixed coordinates) it won't look good on screens of different resolutions. There's no real answer to this question.. scripts have their place, and you can use all the scripts you want... Positioning all of the elements of your layout, however, is not a job for JS. Use CSS for that.
I'd start here: Starting with HTML + CSS
There is not one method for all situations. Each web application needs to employ the right tools and practices to achieve its goals. This varies so much between applications that there is not a "correct" answer to your question.

Which of these jQuery JavaScripts will have better performance?

I have sections with headers. Clicking the header collapses and expands the section below it. A class is also applied or removed to the header for styling purposes. There are 9 of these sections and headers.
$('.header').click(function() {
$(this).toggleClass('open');
$(this).next().slideToggle();
});
Im trying to improve performance for mobile devices. I dont mean page loading times, rather the smoothness of the animation and delay after touching the header before the annimation fires.
Ive read that using IDs is faster than Classes. How much faster will the following be? (note, it would need to be repeated 9 times and ive shown the first 2). Im also assuming using an ID is faster than traversing the DOM with .next(), how much difference will this make?
$('#header1').click(function() {
$(this).toggleClass('open');
$('#section1').slideToggle();
});
$('#header2').click(function() {
$(this).toggleClass('open');
$('#section2').slideToggle();
});
Note, I know its a bit of a crutch but I want to use jQuery not plain JavaScript. The jQuery library will be loaded anyway as its used elsewhere on the site. Thanks
It doesn't matter at all. While ID lookups are indeed the fastest, modern browsers have optimized selector-based lookups so all of them are pretty fast unless you do something that requires iterating over the whole document (such as a [someattribute] selector).
However, $('.header') saves you from repeating code and thus is the way to go. Besides that, it's more readable - in the second example you don't even know where the element it affects is without looking at the DOM.
So, instead of trying to optimize what doesn't need to be optimized, keep your code clean and maintainable!
The second method will be marginally quicker, however the slight gain will be negated by the ugliness and unmaintainability of the code.
Use the first option.
Technically:
The ID reference method is a far faster DOM lookup in browsers that don't support getElementByClassName. But that's offset by having to parse twice the amount of code and apply two click handlers. .live() may be faster still as it only binds to the body and does the lookup later.
Practically:
Very negligible difference. This is micro optimization territory. There are probably much bigger factors of speed in your code than this.
An id as a selector is quicker, but for maintainability do you really want that duplicated code?

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.

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