Render-blocking Javascript and CSS - javascript

It seems to me that anytime there is a <script src="name1.js"> or a <link href="name2.css"> statement in the <head>, these two files block rendering of the markup.
FWIW, I have tried adding "async" to the <script> tag and it totally messes up some of my jQuery plug-ins
Given that, I really do not understand the phrase "Render-blocking Javascript and CSS".
Thanks!

They block rendering of markup because the browser parses the HTML file from top down.
You can avoid this by placing the script tag before the closing body:
<script src="whatever.js"></script>
</body>
You're out of luck with link elements, unless you just use inline style declarations in the head (probably not a good idea).
You can also use the async attribute in the script tag, or you can use one of any numerous async JavaScript libraries.

You can also try to load the critical css first before loading the main/minified css file to avoid render blocking on CSS files.

Related

API embeded code is sending <style>, how do I ignore?

I am using embeded JS code for a service I need included in my website. It is embedding its own <style> CSS along with the HTML elements. It is a new service and there is no support for sending anything else. How can I ignore the <style> so I can use my own CSS to integrate into the theme? I don't want to resort to using !important flags.
As long as you use same classes for your CSS and you include it after the JS code loads it (assuming it loads it synchronously) your classes will override the default settings.
The way the CSS is rendered - if there is a conflict between declaration the instructions passed "later" prevail.
<html>
<head>
YOUR JS HERE
YOUR CSS to override your JS imported rules
</head>
<html>
You need to make sure you understand how CSS assesses the "weight" of the instructions though (important, inline style, id, class, html tag)
https://css-tricks.com/specifics-on-css-specificity/ - here is a decent explanation how it works.
I ended up adding !important to my CSS file since the JS file is loaded asynchronously and it would be more work to keep checking until it is loaded to remove the <style>.

Where to insert JavaScript Libraries and CSS in my HTML code?

I am little new to web development and when I was searching internet about other topics, I have seen many people has put popular JS Libraries in Different Places of their websites.
eg: Inserting JS Libraries on the Very Beginning or Start of the <head> </head> section. (Before loading any JS Code or a CSS File)
eg: Inserting JS Libraries on the End of the <head> </head> section. (After loading all JS Codes and CSS Files)
eg: Inserting JS Libraries on the End of the <body> </body> section. (After loading all JS Codes, Texts, Images, Videos, CSS Files etc...)
So my question is this.
What is the best practice for inserting (where) following JS Libraries, Plugins and CSS Style Sheets to a web page for the most faster loading times and other advantages? - Please mention the reason -
JQuery and it's Plugins
Bootstrap 3.js
Modernizr.js
Angular.js
And another widely used JS Libraries which I couldn't mention here...
Normalize.css
reset.css
bootstrap.css + more
Thank You..!
There is no so called "standard" method. The choice of where to put the lines boils down to one question: When will I need the library?
You see, web files loads line by line, let's take the following as an example of what I mean:
<script>
document.getElementById("target").innerHTML = "changed"
</script>
<p id="target">unchanged</p>
#target isn't altered because the script was loaded before the element did. Web files loads procedurally. When the line of JavaScript is loaded. It is executed immediately, but the target element isn't. So it couldn't change the element.
Even with jQuery, there is the same problem:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("#target").text("changed");
</script>
<p id="target">unchanged</p>
Therefore, we often use $(function(){}).
Back to the loading problem
People who put their <script> tags or <link> tags in the body (in front) or in the head, wanted to execute the script immediately, sometimes they won't use $(function()) or document.onload
People who put their <script> tags or <link> tags in the body (in the end) wanted to ensure all elements are loaded then execute the script or load CSS.
Conclusion
You should load independent resources such as jQuery first, then load dependent resources such as jQuery plugins. Then you try to decide when you want the resources to start loading, then put the lines in places.
You should put CSS links in the <head> tag because you don't want visitors seeing unstyled content before loading the CSS files.
If you can't decide or don't care about the time, put every <script> and <style> tags in the <head>.
Here is another post you might be interested in: Load and execution sequence of a web page?
CSS can added inside header tag & but put all JS Libraries and custom files just before closing closing body tag
<body>
//other tags
<script> All Scripts here </script>
</body>
By doing so you wont have to check if DOM content has loaded.
It decrease page loading time.Otherwise a js need to be completely loaded before DOM loading.
It also makes sure that all events are attached properly to DOM element.
I think this address all your concern specially the third one
CSS Sheets go in the < head >. The order of the CSS files matter so libraries should be put in first then you can put in the specific ones you have.
Javascript links go in the < body > but place them at the very end. That way your HTML content loads first then the JS loads and it will recognize all your selections. It is more efficient to do it this way.
The most important thing to note when placing your css and script tags is that the order you place them determines the order they are loaded in and if style or code is loaded later it over writes the code written before. So if you have css styling that assigns different styles to the same attributes of the same element then it is the one loaded later that takes effect. And with script tags it's important to remember that for dependency reasons. You should load the dependencies first so that they are there for the other scripts to use. Aside from that normally css tags are in the head and script tags at the bottom of your body element

Separating jQuery code from HTML

I'm trying to clean up my code so I'm putting all the stuff in my
<style></style>
In a CSS file. And I'm trying to do the same for my jQuery. So I created a Custom.js file. But do things like:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Stay in html file or can I move them the Custom.js file? Also, I'm using a jQuery plugin called uscrollbar so I have this piece of code in my html file:
<script>
$(document).ready(function(e) {
$('#scroll_form').uscrollbar();
});
</script>​​​​​​​​​​​​​​​​​
Can I also move that to Custom.js?
A much better question.
It's best to keep links to external scripts in your HTML, it's perfectly fine to have a few <script> tags. Especially ones using a CDN!
You can move your document.ready() function to external JS, where all of your other JS is kept. But sometimes it's easier to include small snippets like that directly in pages where it concerns only that page.
When moving things to separate files, it's important to include them in the right order.
Usually something like Modernizr at the top (<head>), with jQuery near the bottom (just before </body>), followed by your plugins, followed by your custom scripts.
Check out RequireJS, it gives you a super simple way to include javascript files as you need them, rather than stuffing your header / footer full of tons of <script> tags.
Keep your references to Javascript files (local or remote) in your HTML code. Place them at the bottom of the page before the closing body tag if they do not need to be ready until the DOM is ready. For instance, your jQuery reference should almost always be in your 'head' section because any references to jQuery while the HTML loads need to be defined even though functions that aren't called until after document is ready do not need to be defined. Many other supporting files like 'jquery.easing' for instance, can go at the bottom which improves page load times.
You can move the uscrollbar() call to a .js file, but I would recommend putting all of your "ready" commands in one function, and then in your HTML simply call that function on ready. IE:
<script type="text/javascript">
jQuery(document).ready(function() {
fn_LoadFunctionName_Thats_InYour_Custom_js_files();
});
</script>
Don't forget to include type="text/javascript" in your script tags.
If you're using custom js that's more than just one little function call, I'd separate into a new js file and just call that in your <script> tag. Same with css. If you're changing styles with your jquery, then usually I use addClass, removeClass, and toggleClass to modify my styles. That way you don't lose track of your styling from css to js files.
You can certainly move them to Custom.js file. Just make sure you have included the file in your html file as you've included the jQuery library.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="Custom.js"></script>
Just make sure the path for Custom.js is correct. Also, you don't put script tag in the js file. So the Custom.js would be:
$(document).ready(function(e) {
$('#scroll_form').uscrollbar();
});

Where to place JavaScript functions: <head>? <body>? or, after </html>?

I'm confused about where to place JavaScript functions:
When should they be put within the head
When inline within the body
And, when after the closing html tag?
thanks
The rules are fast and loose on this, There is no right or wrong way only better and less-better. (well after the </html> is wrong)
Generally speaking, javascript in the head of the document might block rendering of the page until the file is loaded in some browsers *cough*IE*cough*. This is due to a limit of simultaneous connections. So some people put them before the closing html tag. You can use a library to asynchronously load the javascript to avoid this blocking.
If you're using a library, or checking for the DOM to be loaded before executing code there's really no issue of where it's placed. However if you're not doing that it's probably better to put it at the end.
Javascript can always be safely placed in the head to make the functionality available to the entire page. Note that this can block loading of the rest of the document, so if you are loading very large or external Javascript, you may wish to load them inline near the end of the body.
Javascript placed inline will become available when executed. This allows you to conditionally load JS when page elements are loaded.
Javascript should always be placed in the <head> or <body>, never after </html>.
I agree, never seen (nor could I recommend) after html. Also, as noted, blocking is the concern. What I often go with is one script reference in the head to yepnope (an async js loader and testing tid bit (now included with modernizr)), and a tiny block of inline js at the end of the body tag that loads a bootstrap js file.
In that file, I use another yepnope request to load other needed assets asynchronously, and kick off initialization methods.
I've also taken to putting my Google Analytics code in a final yepnope block, so that it's the last thing to load, even after the js app boots.

Use some CSS only if user has JavaScript enabled

In order for my webpage to degrade gracefully, I have some CSS that should only be loaded if its corresponding JavaScript will function.
What is the simplest way to load local CSS if and only if the browser has JavaScript enabled?
Also it's quite a big block of CSS, so I'd rather not have to write a JavaScript line to add each attribute. (Oh, and if necessary I can use jQuery).
Set a class on the body tag of "noJS". Then use Javascript to remove that class.
For the CSS rules that you want to be used when no JS is present, just use .noJS .myRules {}
In the <head> you can include it with document.write(). I've never tried this, but it should work in theory. No script execution means no stylesheet loaded.
<head>
<script type='text/javascript>
document.write("<link rel='stylesheet' href='your.css' media='whatever />");
</script>
</head>
You have a few options.
The one I like is to add the following code to the body tag.
<body id="no-js"><script>document.body.id="js"</script>
Then I can target #no-js and #js from my master CSS.
An additional option is to load an extra stylesheet with JavaScript, but that will slow down you initial load, which I try to avoid.
Check out the body conditionals for html5 boilerplate to see how to employ modernizr.
Also good example here: http://webdesignernotebook.com/css/how-to-use-modernizr/
Then write your css selectors for .no-js .addl-selector {}
I simply do this:
document.documentElement.className = "js"
This adds class js to <html> tag, then you can target your elements by css using:
.js #someid{}

Categories

Resources