jQuery: Move JavaScript to the bottom of the page? - javascript

We are developing large ASP.NET applications with lot of dynmically created pages containing ASCX controls. We use a lot of jQuery everywhere.
I have been reading that it would make sense to move the inline JavaScript code to the bottom of the page as it could delay the loading of the page when it's included "too early".
My question is now: Does this still make sense when working with jQuery?
Most of the code is executed in the ready handler, so I would expect that is does not slow down the loading of the page.
In my case the multiple Usercontrols ASCX have all their own jQuery bits and pieces, and it would not be easy to move that all down in the rendered page.

Placing scripts late in the HTML is recommended because loading and executing scripts happens sequentially (one script at a time) and completely blocks the loading and parsing of images and CSS files meanwhile.
Large/lagged/slow-running scripts near the top of the page can cause unnecessary delay to the loading and rendering of the page content/layout.
Script's size (download time) and complexity (execution time (dom traversal, etc.)) factor in - but more importantly, the number of individual <script> HTTP requests matters far more (the fewer requests the better).
Using the "document.ready" handler lessens the delay caused by slow execution - but still leaves the problem of the sequential HTTP overhead.
Recommended reading: High Performance Web Sites by Nate Koeckley.

You could model the different ways of ordering the JavaScript in Cuzillion to see how it affects page loading.
See the examples and this blog post for examples of how ordering of page elements can affect speed.

When you include JS then the loading of the page from that point will defer because of that the JS file might contain a "document.write" statement.
This means that the entire page will STOP being rendered from the point where you include your JS files and make the browser go "white" or something (at least not display the rest of the page) so the short answer is definitely yes...!
(Longer answer is "probably" with 99% probability)
As in move the inclusion of JS (and also inline JS - which you shouldn't use BTW) to the bottom...
When that's said if you're on ASP.NET you shouldn't use jQuery but rather Ra-Ajax which BTW have all these "best practices" automagically included for you...

Most of the time, the reason to move your JavaScript to the bottom of the page is to ensure that any DOM elements the JavaScript might reference have been created before the JavaScript is run. This also ensures that the page has time to render before running any JavaScript.
In this case, I wouldn't worry about moving the JavaScript down lower on the page.

Related

Put jQuery at the bottom of the code

it's not the first time that I'm restyilin' my website and there's always this problem: when I analyze the page with the Google PageSpeed, it suggests me to put the Jquery and a few other .js codes at the bottom of the page to increase the loading speed.
The problem is that most of the time when I do that the slider, in this specific case, do not work.
Is there an easy solution for this?
I already minified and included the jquery on my wesbite as (jqu.js)
It's not always the case that jQuery can be loaded in the footer of the page. PageSpeed Insights does not catch the cases when this occurs, and thus will always give you a penalty. I'm familiar with this happening with various Carousel-type Javascript UI elements; it sounds like your slider is affected too.

Best practice - pre-write HTML in document with display:none, or create with JS?

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.

Is it safe to substitute html <script src="xxx.js"> 'includes' with $.getScript(...)?

(I am still very new to Javascript and JQuery) I am trying to keep my code clean by creating one js file per html file. I also have a couple of common js file containing code used by page-specific js files.
I was searching for solutions to import/include other js files in a given js file and I came accross this one. It refers to $.getScript().
Instead of using multiple <script src="xxx.js"></script> as imports/includes in my html pages, could I move them to my js files and use $.getScript(...) instead? I mean, is it safe? Is it a good practice?
EDIT
Is it safe regarding cyclic references?
EDIT II
To make it more clear, let's imagine I have a1.js, a2.js and a3.js.
For a1.js:
$.getScript("a2.js");
$.getScript("a3.js");
...
For a2.js:
$.getScript("a3.js");
...
For a3.js:
$.getScript("a2.js");
...
There is a potential infinite loop between a2.js and a3.js. Should I handle it with something like this in each js file:
var vari;
if (typeof vari === 'undefined') {
vari = 1;
}
Regarding good Practice that answer is as always... it depends.
Your Page Style
Contra:
If you for example use a script to substitute some page fonts, the effect will be that the font change will be even more visible for the user.
If your script changes the height of some elements, this will be very noticeable.
PRO:
If you load a Script to handle a specific form, that the user first has to edit, there is no problem at all
If you load a Script that starts animation that can be substituted with a single loading animation you can do this.
If your page is a application with many views and models, you can use getScript like getJson, in this case your page speed will greatly improve.
Your Coding Style
Not every Page and Script is structured to be used this way. JQuery's $(document).ready() fires every registered handler once, even after the event occurred. This does not necessarily mean every handler works this way, certainly not the DOM2 Events.
If you have anywhere inline Scripts it will no longer work.
You can no longer guarantee a certain order your initialization code will have, so you can run in problems have to add more checks, that e.g. a expectedly visible container is still visible.
Whats the reward?
On high performance pages, you gain some thats clear. But script tags at the end of the page can do the same thing with half the work (mainly: remove inline scripts). In my opinion getScript is something like a last reward, you should not overuse it, because the potential to not only scare other developers but also your customers away is clearly there. I would only use it in the environment of a web application, because here are the real benefits
UPDATE response to your comment
Using getScript on your page should look like this:
//since you need it there will be some kind of wrapper
var initClosure = function() {...}
if(typeof optionalNamespace == 'undefined') {
$.getScript('/foo.js', initClosure);
} else {
initClosure();
}
All depending code is in initClosure, and you check a namespace, or variable name (even something like window['blub'] or simply blub will work). You will need this, since the on getScript depending function, wich typically sets default values or appends something to the dom should only be called once.
Nevertheless I don't really see the point in cyclic references, because this would mean:
load script 1 -> wait -> loaded ->load script 2 -> wait ->loaded -> [...] ->load script 1
This situation should be avoided for at least 2 reasons
The browser can not predict this. If there are several script tags, your browser will take care of parallel downloads, so the overall speed (simplified & rough) is the time the biggest file will need to load. In my Example it will take the sum of the script loads.
Initialization of your scripts will be handled twice, so any state will get lost.

does inserting javascript code at the beginning of the body affect SEO?

is there any concern of adding javascript code at the very beginning of opening tag of body?
does it affect SEO??
Thanks for your help
No, but for reasons of speed I suggest to insert it at the end of the body.
Why don't you put it in the head section so it's all loaded up for you before the page renders? In my experience, the more code you just randomly litter in the body of the HTML page, the more likely there will be conflicts, especially if one subset of JavaScript requires another subset to load or run first.
Of course, if you must put the code in the body, the best place is right before the closing body tag. Sometimes this is necessary.
The best place to put it is at the end, as page rendering blocks when loading JS. Mind you that the Google crawler won't care but your users will
Yes, because speed is a direct and indirect (via usage metrics) important performance factor for the search engines.
It depends which script, it is recommended to put it at the end to increase load times, but if it is a "low weight" script and it is important to you you can put it on the top and check the load time , if you are still in the "green" area then it is OK. If your site will take 0.5 sec longer to load it will not crash all your SEO efforts.

What's Pros and Cons: putting javascript in head and putting just before the body close

Most of javascript and web development books/articles says that you must put CSS in the head tag and javascript at the bottom of the page.
But when I open html source of famous websites such as this one stackoverflow, I find they put some js files in the head tag.
What's Pros and Cons of both approaches and when to use which?
Found another question for the same issue:
Where should I declare JavaScript files used in my page? In <head></head> or near </body>?
From Yahoo's Best Practices for Speeding Up Your Web Site:
The problem caused by scripts is that
they block parallel downloads. The
HTTP/1.1 specification suggests that
browsers download no more than two
components in parallel per hostname.
If you serve your images from multiple
hostnames, you can get more than two
downloads to occur in parallel. While
a script is downloading, however, the
browser won't start any other
downloads, even on different
hostnames.
In some situations it's not easy to
move scripts to the bottom. If, for
example, the script uses
document.write to insert part of the
page's content, it can't be moved
lower in the page. There might also be
scoping issues. In many cases, there
are ways to workaround these
situations.
An alternative suggestion that often
comes up is to use deferred scripts.
The DEFER attribute indicates that the
script does not contain
document.write, and is a clue to
browsers that they can continue
rendering. Unfortunately, Firefox
doesn't support the DEFER attribute.
In Internet Explorer, the script may
be deferred, but not as much as
desired. If a script can be deferred,
it can also be moved to the bottom of
the page. That will make your web
pages load faster.
Therefore, in general, it is preferrable to put them at the bottom. However, it isn't always possible, and it often doesn't make that much of a difference anyway.
As other people have said, when you put javascript in the head it delays the rendering of the page until after the scripts have loaded, which means the page may take longer to load - especially if you are downloading large script files.
If you move your script tags to the end of the page, you will ensure that the browser downloads images and stylesheets before the script tags and the page will likely apear to be rendered before the scripts start to run. This also means that if you are depending on some functionality from your scripts, this will not be available until a bit after the page is visible to the user.
If you are adding styles or elements (etc. switching textfields with some form of richer editor) this will be visible to the user as flickering.
If you are adding click-events to elements, they will not be clickable until a bit after the elements themselves are visible.
Sometimes theses issues requires you to put your scripts in the head, other times you will be fine by sticking them in the bottom.
IMHO (completely against YSlow and lot's of clever people) you should keep your scripts in the head tag, and just rely on them to be cached most of the time.
In general you should place script references at the bottom of your page. Scripts not only need to be downloaded, they must also be evaluated and executed before the block is released and the page proceeds with the rendering process. Things like Modernizr should be placed in the top because it does some feature detections as well as HTML5 shims that you will probably want.
Another reason you want to try to place scripts at the bottom of the page is Single Points of Failure or SPOFs. This is where a script call times out or for some other reason blocks the page execution. This can happen a lot with third party advertising libraries, etc.
Yes you may have to think a little harder about how you architect your application, but I found it to become very natural very quickly for me. I have built hundreds of web apps over the past 4 years with the script at the bottom and I can tell the difference. I may be 500ms it might be 5000ms but it all matters.
It really depends on your website. If you are accessing and invoking the JavaScript functions inside the body then it must be referenced in the header so that is is loaded. Else if you are only going to call the JavaScript when the whole document is loaded then it is wise to put the JavaScript at the end of body. By putting .JS file at the end you load the whole page and then fetch the .JS file. This way the user will be able to quickly see the page and by the time he/she gets familiar with the page the .JS file has already been downloaded.
Any javascript in the head will be evaluated before the page is loaded, meaning the page feels like it takes longer to load. It is slightly harder to get events to work properly if all the javascript is at the end, but jQuery pretty much solves this problem for you.

Categories