JavaScript and CSS order - javascript

I have an HTML file which is linked to CSS file and also to JavaScript file.
Is JavaScript executed first and then the CSS is applied, or vice versa ?
Is there any way to change the order ?
Thanks !

It's generally considered a good idea to import your scripts as late as possible, and your stylesheets as early as possible. If possible, in fact, you should stick all your script imports at the very end of the <body>. I find that problematic when there are components pulled into the page that want to be able to drop little script blocks that reference jQuery (for example).
If your stylesheets are first, that helps make sure the browser applies styles before showing anything to the user. Conversely, by including scripts last, you defer that potentially slow script processing until after the point where the user gets to see something on the screen.

The JavaScript gets executed when the <script> element is parsed. Some of the JS might set up event handlers to run some JS when events happen.
CSS is applied to the live DOM. Changes to the DOM get CSS applied automatically. Changes to CSS apply to the whole DOM automatically.

Yahoo's research into speeding-up page loading times should be very helpful, and they explain things much clearer than I can.
http://developer.yahoo.com/performance/rules.html

Related

Semantic UI CDNJs Links best practice to put with jquery in header or below footer?

What is the best practice:
putting semantic ui cdnjs links in header under semantic ui css,
or put it in scripts tags below the footer of the page
I found a lot of guys just put it in the header with JQuery too, but as i know scripts must put under the page to be sure every element just created to give it anything with javascript.
Is it correct what i know or there is something i don't know about it? I'd be grateful for any help.
It is correct that generally scripts should be added at the end of the page, as they are loaded last there. This, however, doesn't guarantee that the DOM has been completely loaded at that time (like images etc.), therefore js that depends on that should always listen to the $('document').ready()-event and for that code it doesn't really matter where it is in the html. (A lot of people wrap everything in that listener even if it isn't necessary, just in case)
Bottom line, it is considered best-practice to put any scripts at the bottom of the html, but it isn't always necessary. I would probably do it anyways.
This will also make the js be loaded last and usually that is the least important part of your website (when loading).

Styles are not applied immediately after a <style> tag is inserted

I have a 3 step process:
Insert widget's HTML into the page.
Insert widget's style into the page.
Read some CSS properties from some elements, and based on values set some other properties.
And everything works fine. Except in some rare cases at step 3 the styles (inserted at step 2) may not be applied yet. This usually happens when a lot of stuff loading and gets initialized on the page in parallel with my code.
I can't extract a simple reproducing example (codebase is very very complex).
My question is: is it guaranteed that after styles are inserted they are immediately applied? If not, are there any APIs that would allow me to run some code after styles applied?
I couldn't find anything about this online. So I would very appreciate if someone could direct me to anything on the subject.
The style insertion looks something like this:
var style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.appendChild(document.createTextNode(css));
document.getElementsByTagName('head')[0].appendChild(style);
Seems like <style> content is not applied until every <link rel="stylesheet" /> before it in DOM is loaded.
It may work in this way because styles are dependent and rely on order (if there are several rules with the same selector). According to that - browser developers may execute styles in their order in DOM.
Try to wait before adding your style tag:
till window.load event (for testing)
till all stylesheets are loaded (in production to reduce delay) like here How to determine if CSS has been loaded?
P.S. I haven't tested that
Like any other dependencies, CSS files needs to be fetched/parsed/painted. It's difficult to really know exactly when it's going to be downloaded and used.
I think your edge-cases are when it hasn't downloaded fast enough. Would it be possible for you to have the CSS ready to go and use a class on the body to apply the CSS when needed?

A way to make JavaScript style changes happen before css is loaded

So on my websites I need to make sure that everything still works even when JavaScript is being blocked, which means that things that I want to hide until someone clicks on something have to be shown with CSS and then hidden with JS, which makes it look glitchy when the page is loading because the JS files are always loaded after the CSS stylesheets.
Is there a way for JS style changes to happen before CSS is loaded? Like, stop the CSS from loading with JS, make the necessary changes, and then continue loading the other files, maybe?
If you really want to load your css-file after some code of your javascript:
1. Don't specify a href attribute of you css:
<link rel="stylesheet" href="" type="text/css" media="screen" id="my-style">
Add this in your code (may be the last line of your javascript):
$('#my-style').attr('href','style.css');
And your css-file will be loaded only after that line of javascript
Try adding a .js-enabled class to HTML the tag with an inline script at the top of the head tag. You can then have CSS hide the scripted stuff for you while the rest of the scripts load.
Updated answer (see comment below):
If JS is blocked, you need to either choose to detect this and serve content based on that, meaning backend code, or make use of another strategy such as <noscript>.
Original answer:
which means that things that I want to hide until someone clicks on something have to be shown with CSS and then hidden with JS,
I would always start with display:none or visibility:hidden (see elsewhere for difference between the two) in the css, and use the JS to reveal the element.
There are several ways to solve your problem. What you need to know is the difference between blocking and non-blocking content. Every script and css (media=screen) is immediately invoked. So if you put some css in there in your head, and append something with JavaScript later on, you indeed might seen it shortly in a 'non javascript' way.
To combat this you could have the objects initial state represent the html/css as if the JavaScript has been loaded. (Most ideally you would have serverside rendering, but for simpler sites thing isn't always needed). The downside of this method is that if you have an JavaScript error which prevents further execution, you have a broken state. And if you also neglect the few people that have JS disabled, you're save and rendering looks fine again. Furthermore! You can improve on your sites performance by loading the scripts asynchronously.
If you want a different approach, you can add a className to your html eg <html class="noscript">. Then when all your JavaScript has been loaded, you remove the className. This way you only have one redraw, and it looks progressive. There is a downside to this approach though, since bad performance becomes increasingly visible (since the first time your browser rendered and the time the JavaScript is done could take a while). So ussually this method is not preferred (though looks better than the first for non-js/js disabled browsers).

Why not use inline CSS if all the HTML+CSS is generated at runtime by javascript and no developer will need to work with css and html?

The only reasons I see on the internet to not to use inline-css is because of the separation of html and css & management, but if this is not a problem in my case I don't care I will use.
Another pro I can say is this: imagine you want to load a widget made by another user, you will only need to load 1 file, the javascript and not the css.
But it might have other problems?
thanks
If you read your question again, you have answered it yourself. There is a reason for the "separation" of html and CSS. Because at some point in time, you will eventually want to change the look of what you have coded up. These are the times when having a separate CSS file would be very helpful so you are only ever making changes in one place and not throughout your application.
EDIT
Another usefulness of having the CSS separate is the caching. Most of the modern browsers cache the CSS files. This means there are less round-trips to the server and quicker response times. I'm not sure if same is the case for JavaScript, because JavaScript files would be cached, but the client browser will have to execute the code every time it loads.
I think this is a good question that is worth exploring. I don't think there is a performance or standards-based argument for not using inline CSS - it works perfectly well - the only (though considerable) argument for separated CSS is for maintainability / readability. And so if you are generating CSS from JavaScript, generating it inline is just as sound as any other way.
In fact, DOM APIs in general expose much simpler methods for assigning styles directly to elements ( https://developer.mozilla.org/en/DOM/element.style ) than for creating new stylesheets. Therefore almost all JavaScript libraries, like jQuery, when they have to manipulate styles they do it by adding inline styles to an element.
Having said that, I have never before seen a situation where the mark-up and styling for a whole page was generated with JavaScript. I would expect this to be rather inefficient. I can see that if you have a web application where all content is pulled in through Ajax (a perfectly good solution) then you might write a fair bit of the mark-up with JavaScript, but still it would be better/more efficient to load most of the surrounding mark-up for your content in the initial page load, and then use JavaScript to swap out content within existing elements.
In any case, I would recommend that you keep most of your CSS in an external stylesheet with relevant classes already defined, so that all your JavaScript does is create elements with the correct class. This would have a performance advantage and would also mean that all your style information was located in one place, and is separate from your JavaScript, which would make your code easier to maintain.
It's OK to use inline css. (in this specifice case)

Initiate onclick faster than with document.onload

I have html-pages with links where i want to attach a function to their onclick event. One way to do it is of course:
Save
But I know this is not the best practice. So instead I wait for window.onload, loop through the links and attach the save-function to the links with rel="save". The problem with this is that it waits until the whole page has finished loading which can be several seconds after the link is displayed and clickable.
So is there another way to do this? Avoiding onclick in the html but that makes it work immediately when the link is rendered.
Internet Explorer has a handy attribute for <script> tags called defer. It's for delaying the parsing of a script until the document has finished loading. For other browsers that support it, you can use DOMContentLoaded, as someone else suggested and for browsers that don't support either you can fall back to onload.
<script type="text/javascript" defer>
//- Run this code when the DOM parsing has completed
</script>
I did a quick Google search for "DOMContentLoaded defer" and found the following page that might help:
http://tanny.ica.com/ica/tko/tkoblog.nsf/dx/domcontentloaded-event-for-browsers
In your case, you can just leave that as it is. Stick to the simplest possible thing, even if it is not the general best practice.
You could try DOMContentLoaded event instead of load. IE also gives you the defer attribute for script tags, which defers execution until the DOM is loaded. If those don't work for you, then you are stuck with the solutions you mention, as far as I know.
I don't know if this is appropriate for your solution, but you could insert script immediately below the are with the links you need altered. This script would not be wrapped in a function, allowing the browser to execute it immediately when seen. The effect is that you can run script before the full page is loaded, altering only the items that exist above the script being run. (If you reference something below the script, it will fail.)
BTW, this is almost certainly not a best practice, and some would probably label it a worst practice.
How about this?
Save
Note: This solution requires to users to have Javascript enabled. Not exactly best practice, but may be suitable for your scenario.
The ideal here would be to use the ideas of Unobtrusive Javascript.
In this way, if the Javascript isn't loaded the link would still do something. It's a link right, so it leads the user to another piece of content? - this should work without Javascript. And if the functionality attached to the links can ONLY work with Javascript you should create and insert them into the DOM with Javascript (they aren't clickable if they aren't there...).
(Otherwise how about delegating the click event to a wrapper element? Does that work before the element is complete?)
edit: Oh, and "save" sounds very much like it ought to be a button in a form rather than a link. The Unobtrusive JS stuff still applies though.

Categories

Resources