I'd like to separate my JS code from HTML as much as possible and I can see several patterns for that.
1) I can use
$(document).ready(function() {...})
just before closing body tag
2) I can just put js code like
new FormValidationHandler()
in script tag just before closing body tag
3) I can point external js file containing initialization like $(document)ready or new FormValidationHandler in script tag
4) there is also a way to use self-invoking function but don't know if it maps to this problem
My question is which way is preferred?
Second one is that there are two places I can put my external scripts into the web page:
in the head tag
in the body tag (usually at the end)
Should head contain only code that doesn't have to run on page load? Then that code should be placed in body?
there is how I like to do. It's probably not perfect, but I like it this way :
Script location in the HTML document :
Every script loaded at the end of the HTML doc, just before the closing body.
There's one exception : the script that handles the FOUC (modernizr for example). This script must be in the head.
I don't see any other reasonable exceptions.
Scripts organization :
Their's two cases for this, in my opinion : If you work with an Hypertext document, or a web app (Maybe this could need some more explanations, but it would be long :p ). I rarely worked for web apps, so I don't yet have a validated organization for this. But I think in a web app you can probably use some script loading libraries like requirejs and it will probably be more useful than for simple web pages.
For a Hypertext document (most web pages), I like to distinguish two kind of scripts : libraries and what I call in french "script d'interfaçage" ("linking script" could probably be a good translation...).
Libraries are, as the name says, scripts that loads libraries in the javascript environment, but doesn't DO anything.
linking script is made to link those libraries to the specific HTML doc.
For me, in a perfect world, there should be as much library scripts as you which but only one linking script for each HTML doc. In this script you'll find the $(document).ready call if you're using jQuery, and all the content of this script should be very very very simple. Ideally there should be, in the document ready function, only instructions like :
$('my selector').MyPlugin({
option1:'value',
option2: 'value'
});
This type of instruction is really a simple link between the HTML doc and the JS library, and it's very simple to read and understand.
Over this organization, you can than do any kind of packaging to reduce the number of js files to be loaded. This packaging have to be optimized for client caching and limiting HTTP requests etc...
External files or inline scripts ?
Personally, I prefer to use external files for all scripts, but generally I use one inline script tag to declare some variables needed for some libraries (your key for your ad service etc...).
Loading of external libraries
One last specific case : When you have to load a script from another host. Generally, you can't tell if the script will load or not, because you can't tell if the other server is up or not, and if it will be slow or fast... You can't tell exactly what this script will do, so it could break your page...
Loading scripts from other hosts can really create problems, and this is why I recommend loading them asynchronously, once your page is fully loaded, with as much controls as you can.
To do this, I personally developed a library dedicated to loading libraries (maybe one day I'll publish it on gitHub, when I have some time).
For example, I use this script to load Facebook google+ ou twitter APIs, or any other external libs like stat counter or ads services.
Related
I referred the documentation but didn't quite understand it. While working on Javascript with jQuery, I always wrote scripts in the <head>. So why should I write dojo scripts in <body>?
That's not solely Dojo. Loading JavaScript files in your head, means that the entire page is blocked while the <head> is being loaded. Considering the fact that most browsers only support up to 2 simultaneous downloads it means you might be staring at a blank page for a while until the scripts are finished loading.
More can be found at Best Practices for Speeding Up Your Web Site from Yahoo.
The Hello Dojo! tutorial says,
We have also placed the <script> block in the body of the HTML document. We could place it in the header and things would have worked the same, but when you end up in a situation where your application loads a lot of code, having the <script> blocks in the header can keep the page from rendering while they are being loaded. This adds to the user perception of the application "being slow" and can degrade the user experience, so we will generally be demonstrating loading Dojo at the end of the body of the document.
Putting it in the body instead of the head means that the browser can begin to render the page before the script has finished loading: which makes the page-load seem faster.
You also can write your Javascript in a seperate Js-File and just link it in the header
like :
<script type="text/javascript" src="myJavascriptInside.js"></script>
No mixin between Html and Javascript. It's also mentioned in Dimitris link
Best Practices for Speeding Up Your Web Site
Here's a snippet from it:
Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.
This is the way we do it and it works great.
Regards, Miriam
I just did a proof of concept/demo for a web app idea I had but that idea needs to be embedded on pages to work properly.
I'm now done with the development of the demo but now I have to tweak it so it works within a tag on any websites.
The question here is:
How do I achieve this without breaking up the main website's stylesheets and javascript?
It's a node.js/socket.io/angularjs/bootstrap based app for your information.
I basically have a small HTML file, a few css and js files and that's all. Any idea or suggestions?
If all you have is a script tag, and you want to inject UI/HTML/etc. into the host page, that means that an iframe approach may not be what you want (although you could possibly do a hybrid approach). So, there are a number of things that you'd need to do.
For one, I'd suggest you look into the general concept of a bookmarklet. While it's not exactly what you want, it's very similar. The problems of creating a bookmarklet will be very similar:
You'll need to isolate your JavaScript dependencies. For example, you can't load a version of a library that breaks the host page. jQuery for example, can be loaded without it taking over the $ symbol globally. But, not all libraries support that.
Any styles you use would also need to be carefully managed so as to not cause issues on the host page. You can load styles dynamically, but loading something like Bootstrap is likely going to cause problems on most pages that aren't using the exact same version you need.
You'll want your core Javascript file to load quickly and do as much async work as possible as to not affect the overall page load time (unless your functionality is necessary). You'll want to review content like this from Steve Souders.
You could load your UI via a web service or you could construct it locally.
If you don't want to use JSONP style requests, you'll need to investigate enabling CORS.
You could use an iframe and PostMessage to show some UI without needing to do complex wrapping/remapping of the various application dependencies that you have. PostMessage would allow you to send messages to tell the listening iFrame "what to do" at any given point, while the code that is running in the host page could move/manipulate the iframe into position. A number of popular embedded APIs have used this technique over the years. I think DropBox was using it for example.
I know that best practice for including javascript is having all code in a separate .js file and allowing browsers to cache that file.
But when we begin to use many jquery plugins which have their own .js, and our functions depend on them, wouldn't it be better to load dynamically only the js function and the required .js for the current page?
Wouldn't that be faster, in a page, if I only need one function to load dynamically embedding it in html with the script tag instead of loading the whole js with the js plugins?
In other words, aren't there any cases in which there are better practices than keeping our whole javascript code in a separate .js?
It would seem at first glance that this would be a good idea, but in fact it would actually make matters worse. For example, if one page needs plugins 1, 2 and 3, then a file would be build server side with those plugins in it. Now, the browser goes to another page that needs plugins 2 and 4. This would cause another file to be built, this new file would be different from the first one, but it would also contain the code for plugin 2 so the same code ends up getting downloaded twice, bypassing the version that the browser already has.
You are best off leaving the caching to the browser, rather than trying to second-guess it. However, there are options to improve things.
Top of the list is using a CDN. If the plugins you are using are fairly popular ones, then the chances are that they are being hosted with a CDN. If you link to the CDN-hosted plugins, then any visitors who are hitting your site for the first time and who have also happened to have hit another site that's also using the same plugins from the same CDN, the plugins will already be cached.
There are, of course, other things you can to to speed your javascript up. Best practice includes placing all your script include tags as close to the bottom of the document as possible, so as to not hold up page rendering. You should also look into lazy initialization. This involves, for any stuff that needs significant setup to work, attaching a minimalist event handler that when triggered removes itself and sets up the real event handler.
One problem with having separate js files is that will cause more HTTP requests.
Yahoo have a good best practices guide on speeding up your site: http://developer.yahoo.com/performance/rules.html
I believe Google's closure library has something for combining javascript files and dependencies, but I havn't looked to much into it yet. So don't quote me on it: http://code.google.com/closure/library/docs/calcdeps.html
Also there is a tool called jingo http://code.google.com/p/jingo/ but again, I havn't used it yet.
I keep separate files for each plug-in and page during development, but during production I merge-and-minify all my JavaScript files into a single JS file loaded uniformly throughout the site. My main layout file in my web framework (Sinatra) uses the deployment mode to automatically either generate script tags for all JS files (in order, based on a manifest file) or perform the minification and include a single querystring-timestamped script inclusion.
Every page is given a body tag with a unique id, e.g. <body id="contact">.
For those scripts that need to be specific to a particular page, I either modify the selectors to be prefixed by the body:
$('body#contact form#contact').submit(...);
or (more typically) I have the onload handlers for that page bail early:
jQuery(function($){
if (!$('body#contact').length) return;
// Do things specific to the contact page here.
});
Yes, including code (or even a plug-in) that may only be needed by one page of the site is inefficient if the user never visits that page. On the other hand, after the initial load the entire site's JS is ready to roll from the cache.
The network latency is the main problem.You can get a very responsive page if you reduce the http calls to one.
It means all the JS, CSS are bundled into the HTML page.And if your can forget IE6/7 you can put the images as data:image/png;base64
When we release a new version of our web app, a shell script minify and bundle everything into a single html page.
Then there is a second call for the data, and we render all the HTML client-side using a JS template library: PURE
Ensure the page is cached and gzipped. There is probably a limit in size to consider.We try to stay under 400kb unzipped, and load secondary resources later when needed.
You can also try a service like http://www.blaze.io. It automatically peforms most front end optimization tactics and also couples in a CDN.
There currently in private beta but its worth submitting your website to.
I would recommend you join common bits of functionality into individual javascript module files and load them only in the pages they are being used using RequireJS / head.js or a similar dependency management tool.
An example where you are using lighbox popups, contact forms, tracking, and image sliders in different parts of the website would be to separate these into 4 modules and load them only where needed. That way you optimize caching and make sure your site has no unnecessary flab.
As a general rule its always best to have less files than more, its also important to work on the timing of each JS file, as some are needed BEFORE the page completes loading and some AFTER (ie, when user clicks something)
See a lot more tips in the article: 25 Techniques for Javascript Performance Optimization.
Including a section on managing Javascript file dependencies.
Cheers, hope this is useful.
We can place JavaScript in 3 ways?
as a external file
in <head>
in body <body>
all methods are valid by W3C ?
So How to judge where JavaScript should be placed at bottom or which must be in <head> or in <body>?
I've seen JavaScript on many sites
in <head> ,
as a external js,
just before </body> and
some time anywhere in <body>....<body>
for example: before any other XHTML
tag/code which are going to affect
with that JavaScript code.
update:
I saw mostly people use Google analytics code as a inline javascript at bottom?
In my coding I follow the following rules with regards to JS organisation:
Any JS that is not time sensitive and/or runs after the document is loaded gets put into an external js file and included in the head
Any JS that needs to run as soon as possible is placed in the DOM where appropriate (eg. if you want some code to run as soon as the necessary elements are loaded place the code directly below the last dependent element)
Any external tracking libraries like Nielsen/Google go right at the bottom just before the closing body tag
Related SO posts:
Where should I declare JavaScript files used in my page? In or near </body>?
Does javascript have to be in the head tags?
In most all cases, Javascript should be as an external file, to allow caching and avoid re-downlading the exact same 100+-line script on each page load. (If, on the other hand, it is a script you only expect users to ever see once, then inline is fine.)
Whether or not it goes in head or body is really your choice, though Yahoo recommends the bottom of the body for performance.
If you're concerned with page load times this google article on minimizing your payload size might help. I've linked to the section relating to deferring the loading of javascript. Not exactly what you asked for but might come in handy.
In fact, http://code.google.com/speed/ is just plain handy!
I generally will place as much as I can into external js files. The main exception to this, is information injected into the page server-side at load. I tend to push everything that is not specific to the one page into a library/site js file. If you don't have a need for inline scripts (ie: document.write), then it's best to push your scripts to the bottom before the closing body tag (see YSlow and yahoo's research on why).
If the page/script doesn't NEED document.write, put it at the bottom.
If it does NEED document.write evaluate why.
If it can easily be externalized (into a separate .js) do it.
If it isn't specific to the one page, put it into a .js that is used by multiple pages.
Merge custom site scripts into a single .js where possible.
minify/reduce said .js and use http compression wherever possible.
The primary reasons for this:
Separate your markup from your scripts.
Separate your markup from your scripts.
Separate your markup from your scripts (as much as possible, same as for css)
Create reusable script includes to reduce server requests.
Reduce server requests
Reduce the time to transfer your files.
I'm working on a project which uses many scripts (Google Maps, jQuery, jQuery plugins, jQuery UI...). Some pages have almost 350 kB of Javascript.
We are concerned about performance and I'm asking myself what is the best way to integrate those heavy scripts.
We have 2 solutions:
Include all scripts in the head, even if they are not utilized on the page.
Include some common scripts in the head, and include page specific ones when they are needed.
I would like to have your advice.
Thanks.
For the best performance I would create a single static minified javascript file (using a tool like YUI compressor) and reference it from the head section. For good tips on website performance check out googles website optimizations page.
Note that the performance penalty of retrieving all your javascript files only happen on the first page, as the browser will use the cache version of the file on subsequent pages.
For even better responsiveness you would split your javascript in two files. Load the first with all the javascript you need when the page loads, then after the page loads load the second file in the background.
If your interested, I have an open source AJAX javascript framework that simplifies compresses and concatenates all your html, css and javascript (including 3rd party libraries) into a single javascript file.
If you think it's likely that some users will never need the Google Maps JavaScript for example, just include that in the relevant pages. Otherwise, put them all in the head - they'll be cached soon enough (and those from Google's CDN may be cached already).
Scripts in the <head> tag do (I think) stop the page from rendering further until they’ve finished downloading, so you might want to move them down to the end of the <body> tag.
It won’t actually make anything load faster, but it should make your page content appear more quickly in some situations, so it should feel faster.
I’d also query whether you’ve really got 350 KB of JavaScript coming down the pipe. Surely the libraries are gzipped? jQuery 1.4 is 19 KB when minifed and gzipped.
1) I would recommend gather all the common scripts and most important like jquery and etc in one file to reduce number of requests for this files and compress it and i would recommend google closure u will find it here
2) Make the loading in a page the user have to open it in the beginning like login page and put the scripts at the end of the page to let all the content render first and this recommended by most of the performance tools like yslow and page speed
3) don't write scripts in your page , try to write everything in a file to make it easier later on for compression and encryption
4) put the scripts and all statics files like images and css on other domain to separate the loading on your server