Where to load javascript scripts in html page - javascript

I am developing a jquery page and I think it is a little bit slow when you load it because I load all js files at the begining.
Would it be faster if I load just which I need at the begining and in each section, loads which I need?.
Now my webpage has all script calling in and after that, in all sections, home, page2, page3...
I structurated the webpage in one html file and I navigate to each section. Each section is like this:
<div data-role="page" id="secion2" data-theme="e">
<!--<script type='text/javascript' src='javascript/createFbAlbums.js'></script> -->
**LOAD SCRIPTS HERE**
<div data-theme = "f" data-role="header" data-id="fixedNav" data-position="fixed">
<h1>Page 2</h1>
</div> <!-- /header -->
<div data-role="content">
<ul data-role="listview" data-inset="true" class="managementEvents">
<li data-theme = "f">Page2</li>
<li data-theme = "f">Modify Exposiciones</li>
</ul>
</div> <!-- /content -->
Loading them in sections like the commented in this piece of code. Is this equal to load at the begining or not?
Or doing something like this inside javascript:
$(document).on("pageinit", '#section2', function(){
**LOAD HERE SCRIPTS**
Javascript code here doing everything in that page
});
I am a little bit lost because I don't know if this is ok or will break the page or will not speedup the loading.

The usual recommendation (for instance, in YUI's Best Practices for Speeding Up Your Web Site) is that unless you have a good reason to do something else, put your scripts at the very end of the page, just before the closing </body> tag:
<p>Content</p>
<div>More content</div>
<script src="/some/script.js"></script>
</body>
</html>
Side note: This also makes it essentially unnecessary to use jQuery's ready feature. If the script is at the very bottom of the page, all of the elements defined by the markup above it are available for scripting.
There's lots more useful advice in the page linked above. For example: To the extent possible, combine all of your scripts into a single file. (And make the file cachable, etc., etc.)
The downside: If you have content on your page that requires JavaScript to work correctly, the above means that the events related to that won't be hooked up right away. There can be a brief window of time between the content being available to the user, and the event handlers being registered. To deal with that, the concept of "progressive enhancement" comes into play: Make things work well without JavaScript, and then make them work better with JavaScript. Things that just can't work without JavaScript should be added by the JavaScript, or loaded initially-hidden and then shown by the JavaScript.

Whenever possible, JS files should be loaded at the bottom of the page. Prior to the closing body tag.
http://developer.yahoo.com/performance/rules.html#js_bottom
The reason is that JS files loading can block parallel downloads of other page assets. So they can cause a bottleneck.
In addition to that advice, since you're using jQuery, load jQuery from a CDN such as Google. There are a couple of benefits to doing that:
a popular CDN such as Google increases the odds that the end-user has already cached the JS library
it further reduces the parallel downloading bottleneck as it's another domain (the bottleneck is per-domain)

The recommendation is to put JavaScripts at the bottom of the page. This does not take into account dynamically loading your scripts, however, because there are differences in how browsers actually handle downloading external resources such as JS files between using tags and dynamically loading via JavaScript DOM manipulation.
Further Explanation
Browsers load HTML and any embedded resources synchronously as they parse the HTML. This means that as your page loads, when you have scripts up front, the loading of the page stops, the browser makes a request to download, then parse and evaluate/execute the JavaScript file, and then continues to load the rest of the HTML. It does this with each script.
Therefore, unless there are crucial elements that need to use some JS functions or variables during page load, and in some cases this is needed, it's better to load the JS at the bottom of the page because your page will render quicker. And in those crucial cases, only load enough JS to get the page load done as quick as possible.
As an interesting aside, loading JS files dynamically using JavaScript itself (i.e., dynamically inject script objects via javascript after page load), those scripts will load asynchronously and further improve page load times.
So to answer your question,
If you use the jQuery.ready() method of loading JS, it conforms to a best practice since the scripts will load after the page has already been loaded by the browser. This is in effect even better than placing tags at the bottom of the page.
$(document).ready(function () {
$.getScript( "yourScript.js" )
});
(Full example for jQuery getScript can be found here for more in-depth examples:
http://api.jquery.com/jquery.getscript/

You should always put your scripts at the bottom of your page before closing </body> tag
Refer here for more informations why you should do it.

Yes as everybody mentioned, it won't hurt putting the scripts at the bottom of page before </body> tag whereas it might create a problem sometime when you put the script in the head tag.

It would really be unnecessary to put your script at the end of your HTML if you use $(document).ready(function(){ then add your code, and close it with }) it will have the same effect, although both methods are considered good programming practice.

Related

Why I have to put all the script to index.html in jquery mobile

I have used $.mobile.changepage to do the redirect in my phonegap+jquerymobile projects. However what makes me confused is that I need to put the script of all the pages to the same file index.html. If not, the redirect page can not execute the function in its header.
for example, my index.html seem to be
$(document).bind("deviceready",function(){$.mobile.changepage("test.html");})
then, my device will redirect to test.html which seem to be
$("#btnTest").click(function(){alert("123");})
<button id="btnTest">Test</button>
However, the script will never execute in test.html. Then I put the script to index.html, what I expect to be is done. Whatever, if I put all the script to the same page, the project will become harder and harder to be preserved. Appreciated for your help.
Intro
This article can also be found HERE as a part of my blog.
How jQuery Mobile handles page changes
To understand this situation you need to understand how jQuery Mobile works. It uses ajax to load other pages.
First page is loaded normally. Its HEAD and BODY is loaded into the DOM, and they are there to await other content. When second page is loaded, only its BODY content is loaded into the DOM. To be more precise, even BODY is not fully loaded. Only first div with an attribute data-role="page" will be loaded, everything else is going to be discarded. Even if you have more pages inside a BODY only first one is going to be loaded. This rule only applies to subsequent pages, if you have more pages in an initial HTML all of them will be loaded.
That's why your button is show successfully but click event is not working. Same click event whose parent HEAD was disregarded during the page transition.
Here's an official documentation: http://jquerymobile.com/demos/1.2.0/docs/pages/page-links.html
Unfortunately you are not going to find this described in their documentation. Ether they think this is a common knowledge or they forgot to describe this like my other topics. (jQuery Mobile documentation is big but lacking many things).
Solution 1
In your second page, and every other page, move your SCRIPT tag into the BODY content, like this:
<body>
<div data-role="page">
// And rest of your HTML content
<script>
// Your javascript will go here
</script>
</div>
</body>
This is a quick solution but still an ugly one.
Working example can be found in my other answer here: Pageshow not triggered after changepage
Another working example: Page loaded differently with jQuery-mobile transition
Solution 2
Move all of your javascript into the original first HTML. Collect everything and put it inside a single js file, into a HEAD. Initialize it after jQuery Mobile has been loaded.
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="index.js"></script> // Put your code into a new file
</head>
In the end I will describe why this is a part of a good solution.
Solution 3
Use rel="external" in your buttons and every elements you are using to change page. Because of it ajax is not going to be used for page loading and your jQuery Mobile app will behave like a normal web application. Unfortunately this is not a good solution in your case. Phonegap should never work as a normal web app.
Next
Official documentation, look for a chapter: Linking without Ajax
Realistic solution
Realistic solution would use Solution 2. But unlike solution 2, I would use that same index.js file and initialize it inside a HEAD of every possible other page.
Now you can ask me WHY?
Phonegap like jQuery Mobile is buggy, and sooner or later there's going to be an error and your app will fail (including loaded DOM) if your every js content is inside a single HTML file. DOM could be erased and Phonegap will refresh your current page. If that page don't have javascript that it will not work until it is restarted.
Final words
This problem can be easily fixed with a good page architecture. If anyone is interested I have wrote an ARTICLE about good jQuery Mobile page architecture. In a nut shell I am discussing that knowledge of how jQuery Mobile works is the most important thing you need to know before you can successfully create you first app.
Unlike normal ordinary HTML pages, jQuery Mobile uses ajax technology when navigating between pages. So make sure to import all your JS files and libraries in all your html pages.
If you notice closely you will see that JS files from previous page is taken into consideration when loading the second page. But if you force rrefresh the current page then the js files of the current page will be effective.
So as I said earlier make sure to import the js files in all the html files.
Also no need to call deviceready, use following syntax to call your page specific js functions
$(document).on('pageshow', '#YourPageID', function(){
// Your code goes here
});
Jquery Mobile uses ajax to load a "page". A "page" here is a div with data-role=page. If you load a physical page index.html, you can navigate using changePage to any "page" div inside that page.
However, if you want to load a "page" from other physical page, jQM will only load the first "page" div from that page. What actually happen is you do not change page, jQM just load that particular "page" div using ajax and inject it to your current page.
You have two possible architecture where you put all your "pages" in a html page and navigate from there. Or you can have multiple page architecture. You can always mix this.
To physically change page, you need to add rel=external to your link.

Should use Head.js or just minified scripts before </body> with scripts in the markup?

I have the optimisation problem — my site uses 2 (pretty large) javascript resources:
application.js (minimised jquery, jquery-ui, underscore-js and some shared scripts, 120KB total)
controller-specific file (some modules required for the page + interactions, 4KB total)
I have some scripts in the views that format/convert markup with JavaScript (dependable on both jQuery and my controller-specific JS code) so I need to wait either for $(document).ready or head.ready and it makes the part of website invisible to prevent the flash of unstyled content :(
Now my question comes: should I use head.js for it or just stick with the "before " scripts? Are there any smart ways to speed up page loading time in this case?
Update:
Here's the part of the code (see versusio.com for full code, landing page):
<html>
<head>
... usual stuff
<link (css stuff) />
<script src="head.js"></script>
<script>
// Here some global variables are set like cache keys, actual locale code etc., not dependable on jQuery or any other JS code from the JS assets
</script>
</head>
<body>
... page content
<div id="search">!-- here some code with the "display: none" style to prevent flash of unstyled content</div>
<script>
// Here is code that positions and processes some styles and adds some interactions to the #search div
Application.Position.In.Center($(#search), $(document));
</script>
... more page content
... another "display: none" div and accompanying script
... rest of the page content
<script type="text/javascript">head.js( { 'application': 'application.js' }, { 'landing': 'landing.js' } );</script>
</body>
</html>
First ask yourself this question: Do i really need all this javascript loaded when a user visits my page?
When first loading your website, you actually only need the autocomplete-functionality, the rest isn't needed on load. So you could go for a seperated approach. My advice would be the following:
Build this page without any javascript-functionality and then enhance it with javascript, get rid of the inline styles and scripts.
After you have done this, load the scripts you actually need, you can do this in the head or just before the end of the body
Use a CDN for Jquery, jquery-ui, underscore and the other libraries. If a user already loaded these libraries from another website, you have a performance bonus.
Last of all, already asynchronously load the javascript needed later on, so the user already has the scripts when he hits the compare-button.
Small tweaks:
Use a tool like ySlow or the networking graph in your favorite browser to look for any bottlenecks. It looks like gzipping is not enabled, try and do that.
Do you really need to load the facebook/google/twitter/third-party stuff in the head or could that be done when the page is loaded?
Is the server as fast as possible? It looks like it takes almost halve a second to get the HTML.
I hope i helped you out for a bit, good luck with the performance tweaking!
You could put mask layer that cover all pages with fixed style, then hide or destroy it when loading process finished. That way there's no need to hidden each content, instead it will be covered with mask div
I think, put a load scripts on the bottom of the page (as the last tags in the body). That javascript it will not block the drawing page, like now.
Saw the view source of your page.
There are some inline scripts which can block rendering. Such as this
Application.i18n = {"comparisons":{"off_ratio":
More here. http://calendar.perfplanet.com/2012/deciphering-the-critical-rendering-path/
Quick way: Moving them to the end of body tag.
Best way: They should be loaded as external scripts - with very good cache headers.
May be, you are doing that as - you have to load those messages based on user locale - You can create separate JS files for every locale during your build process - an they can be linked / loaded as external JS files with good cache headers
Another reason, why you might need inline scripts - to take note of the initial loading time. which is not necessary - as the modern browsers provide us with perfomance timings.
http://www.html5rocks.com/en/tutorials/webperformance/basics/
Moving it as an external script file - will also be good for your site security - in case, if you will be trying CSP.
http://updates.html5rocks.com/2012/11/Content-Security-Policy-1-0-is-officially-awesome.
Defer / async attributes.
ga.js is set with async attibute - but other JS files can be tried with defer attributes. Also, as a general rule of thumb, delay loading resources as far as possible,load only when it is needed.
window.onload - $.ready
Starting your script execution with $.ready is always going to be better than window.onload.
because, window.onload fires only after all the images, inner iframes gets loaded.
The following links might be useful.
https://developers.google.com/speed/
The Progressive JPEGs post in http://calendar.perfplanet.com/2012/
http://blog.chriszacharias.com/page-weight-matters
http://www.igvita.com/2013/01/15/faster-websites-crash-course-on-web-performance/
A lot of further optimisations are possible. All the best.

Where should I include javascript on a page?

I am building a Rails app, and it seems that common practice is to have javascript_include_tags listed on top of a page.
Would it makes browers load javascript before loading the document, and thus makes visible elements take longer to load?
Thank you.
As far as I've read on the web, best practice loads javascript files at the bottom of the body tag. This lets almost everything load before executing the javascript, which generally prevents problems accessing items that may not exist if you loaded the script at the top.
A Yahoo post about web page performance suggests including them at the bottom of the page (Source) because they can block parallel downloads of other dependencies if they are at the top.
Looks like some answers were right, but none sums it all up:
How to prevent javascript loading from loading other elements? Simple, put it right before the closing </body> tag. Which usually means a few characters before the end of your HTML page.
Put all your javascript in external .js files. Why? So that the browsers can cache those files even when the HTML page changes.
Aggregate and minify all your javascript files into one. Why? Because the fewer HTTP requests your clients make, the faster the page loads.
Also, you don't have to care about $(document).ready() or window.onload, since all your HTML elements will be loaded before the javascript files (that is, if you put the JS files right before the closing </body> tag).
It's a good idea to use external JS file and to minify it's content.
http://www.quirksmode.org/js/placejs.html
Bottom of the page is also an option like John Fisher said.
If using i.e. jQuery you in any case use $() or $(document).ready(function() which makes sure the page DOM is loaded before you try to use your JS functions.
Rather than embedding the behavior in its markup, try to segregate the script
by moving it to a script block in the section of the page, outside the scope of the
document body, as follows:
<script type="text/javascript">
window.onload = function() {
document.getElementById('testButton').onclick = function() {
document.getElementById('xyz').style.color = 'red';
};
};
</script>
For performance reasons, script blocks can also be placed at the bottom
of the document body, though modern browsers make the performance
difference rather moot. The important concept is to avoid embedding behavioral
elements within the structural elements.

Js, is it really better to include at the end of the page?

Currently I'm doing this.
<js>
</head>
Pagespeed and other articles suggest doing this instead.
<js>
</body>
</html>
I would love the opinion of stack overflow!
Thank you
The only issue with putting all your scripts at the end of the body is that sometimes page components drop little bits of Javascript on the page that may assume the existence of some Javascript facility. Other than that, there's nothing wrong with it and it can help make your pages appear to load/render faster.
You might also look into tools like LabJS (http://labjs.com) as a more sophisticated way to load your Javascript.
Use progressive enhancement so that your page will work whether JavaScript is enabled or not. Then, move the Javascript to the bottom of the page so that your page's content loads and renders first. And, as always, test the performance of your page using Page Speed or YSlow.
The default way of including Javascript is to do it from the head tag, that's where they normally belong. That's where you should start out, and only move the scripts if you need to optimise the loading of the page.
There are some reasons to put some scripts later in the page:
To make the content of the page load earlier
To make the page less sensetive to slow loading external scripts
There are some special considerations if you move scripts down the page:
Some scripts doesn't work if the load after the content.
You should make sure that the content doesn't look bad or does anything nasty if the user tries to use it before the scripts are loaded.

Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?

I've recently read the Yahoo manifesto Best Practices for Speeding Up Your Web Site. They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.
But where exactly and when?
Should we put it before closing </html> or after ? And above all, when should we still put it in the <head> section?
There are two possibilities for truly unobtrusive scripts:
including an external script file via a script tag in the head section
including an external script file via a script tag at the bottom of the body (before </body></html>)
The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users.
If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page.
And for any performance issues do your own benchmarks - what may be true at one time when a study is done might change with your own local setup or changes in browsers.
It's never so cut and dry - Yahoo recommends putting the scripts just before the closing </body> tag, which will create the illusion that the page loads faster on an empty cache (since the scripts won't block downloading the rest of the document).
However, if you have some code you want to run on page load, it will only start executing after the entire page has loaded. If you put the scripts in the <head> tag, they would start executing before - so on a primed cache the page would actually appear to load faster.
Also, the privilege of putting scripts at the bottom of the page is not always available. If you need to include inline scripts in your views that depend on a library or some other JavaScript code being loaded before, you must load those dependencies in the <head> tag.
All in all Yahoo's recommendations are interesting but not always applicable and should be considered on a case-by-case basis.
As others have said, place it before the closing body html tags.
The other day we had numerous calls from clients complaining their sites were extremely slow. We visited them locally and found they took 20-30 seconds to load a single page. Thinking it was the servers performing badly, we logged on - but both web and sql servers were ~0% activity.
After a few minutes, we realised an external site was down, which we were linking to for Javascript tracking tags. This meant browsers were hitting the script tag in the head section of the site and waiting to download the script file.
So, for 3rd party/external scripts at least, I'd recommend putting them as the last thing on the page. Then if they were unavailable, the browser would at least load the page up until that point - and the user would be oblivious to it.
To summarize, based on the suggestions above:
For external scripts (Google analytics, 3rd party marketing trackers, etc.) place them before the </body> tag.
For scripts that affect page layout, place in head.
For scripts that rely on 'dom ready' (like jquery), consider placing before </body> unless you have an edge-case reason to place scripts in head.
If there are inline scripts with dependencies, place the required scripts in head.
If you want to tinker with the position of your scripts, YSlow is a great tool for giving you a flavour if it's going to improve or hurt performance. Putting javascript in certain document positions can really kill page load times.
http://developer.yahoo.com/yslow/
No it should not be after the </html> as that would be invalid. The best place to put scripts is right before the </body>
This is basically because most browsers stop rendering the page while they eval the script that you provide. So its OK to put non-blocking code anywhere in the page (I'm mainly thinking of things that attach functions to the onLoad event, since event binding is so fast as to effectively be free). A big killer here is at the beginning of the page putting in some ad server script, which can prevent any of the page loading before the ads have totally downloaded, making your page load times balloon
If you put it at the bottom, it loads last, hence speeding up the speed that the user can see the page. It does need to be before the final </html> though otherwise it won't be part of the DOM.
If the code is needed instantly though, then put it in the head.
It's best to put things like blog widgets at the bottom so that if they don't load, it doesn't affect the usability of the page.

Categories