I currently have a lot of widgets on my website that do all sorts of jquery functions, animations, ajax calls etc. I have been reading online that it is good practice to try to bundle your js into one file when you can or when it makes sense. Each of my widgets are widely used on my website so it seems like it would make sense to put all the jquery/javascript for these widgets into one file. Now, if I have $(document).ready(function(){}) for everytime I want to invoke a widget's buttons, automatically load some data on doc ready, etc. what would be the best practice for doing this? Not every widget is on every page, so if everything was in one javascript file, would invoking dom elements that are non existent be bad practice?
I guess I am really having trouble seeing the best way to structure my jquery/javascript around my web application to provide best performance.
It is much better to keep js files filled with reusable code, so all your functions in one page that all pages load. I usually use default.js as that file.. then in each of the pages that require specific implementations i invoke the functions that performs specific tasks to that page, inside a doc.ready at the bottom of the page.
That way you're only doing what you need per page. In any case you should try to have functions that perform your tasks in the default.js file rather than very specific js in a file that is supposed to be generically included for the whole site
Related
From what I read here and there I found mixed opinions on the subject (it may be because of the different uses) and I'm a bit confused.
I recently started doing web programming and I'm using java EE. I want to integrate javascript functions in my code. From what I read the best practice is to put the .js files in a folder and use the <script> tag to refer to them.
From there I have 3 questions :
1) Some people say that I need to put the <script src=...> in the <head>tag. Some says it's best practice to put <script> at the end of the jsp file for performances, which is the best practice?
2) Should I put all my functions in a single .js file or create a .js for each jsp page I have?
3) Do I include jquery the same way as my .js files ?
Its up to you, either will work. From my reading/understanding the purpose of adding the script to the end of the body is that you do not block the parsing of HTML by fetching the script(you can also use the async & defer attributes). Here is another topic on the issue.
This is usually dependent on what the JS is doing. You should reuse common functionality and group common things together.
Yes, just make sure you get the order correct. If you are using jQuery in other files or somewhere else on the page make sure you include it first.
Always put your JS file links at the bottom to prevent blocking of parallel downloads.
Depends on how you're using JS. Ideally you'd have a lot of shared JS that you'd want to put into one file so it caches. But if all your JS is unique to every page, there's no benefit to caching.
jQuery is JavaScript, so, yes, you load it just like the rest of your JavaScript.
I am setting up a site that relies on a lot of javascript items and i want to try and set it up so the pages only call what they need.
there are different types of functionality so i am goig to break them into their own js files to make it easy to use.
For example if there is a drag and drop functionality then i will include the js file for drag and drop. within that will be a generic call using a class to turn on the functionality. This way it is only used on a page that uses drag and drop.
This gets more compacted when i have ajax calls some are on change events on a select for example while others are on a button.
I could separate these into different files for each type perhaps.
my concern is if a call needs more parameters to be passed or a different url then where does this code go to make the call?
I don't really want to have code within the page itself if i can help it.
I would love to hear your thoughts on how to best set this up
RequireJS might be your answer:
RequireJS is a JavaScript file and module loader. It is optimized for
in-browser use, but it can be used in other JavaScript environments,
like Rhino and Node. Using a modular script loader like RequireJS will
improve the speed and quality of your code.
This sounds similar to what I'm doing, so here what I've done:
One central file that contains functions that are used pretty much everywhere.
A folder containing files that are used in several places, but aren't worth including everywhere.
A folder containing files that are only used on one page.
Then, simply include the necessary <script> tags and go!
Hmm, have you looked at existing frameworks http://speckyboy.com/2010/05/17/15-javascript-web-ui-libraries-frameworks-and-libraries/?
I'm currently developing a website with ASP.NET and I always check its performance through Firebug...
Now, my question is,
is it better to put all referencing jquery references in Masterpage?
(Reference all first)
or is it better to put specific jquery reference to a specific Content Page?
(Reference specific only)
Thank you!
I would think it's best to put your stylesheets in the master page, as long as they are site-wide styles. You should also think about compressing them into one download, so you reduce HTTP requests.
Maintainance-wise, I would put each reference where it belongs, depending on the scope of your jquery-referencing object.
For instance, if it's something to do with, say, the main navigation, that's present on all rendered pages, and therefore certainly in your master page, then you have better have your $("#navBar") close to your <div id="navBar">...</div>, i.e. on your MasterPage.
If on the other hand it's something related to a specific content page, let's say that shiny carousel (and its specific jQuery plugin) you need on your homepage, you have better have $('myCarousel').carousel(2); close to you <div id="carousel">, i.e. on your HomePage.aspx content page.
And while you're at dispatching stuff to where they belong, if you can tell for sure that carousel plugin is only required on your homepage, you have better include the plugin on your HomePage.aspx content page only.
Not only will you ease your maintainance, but you will also get benefits performance-wise, as you will be more likely to be initializing variables only when they are used, therefore puting a little bit less memory overhead on the browser. Same stuff about loading plugin-related resources (you may not want each and every page load bloated because your master links to every stuff required somewhere on your site).
Generally speaking, I would encourage you to identify any libraries or plugins which you would be using on multiple pages and include them in a place which will automatically put them within those pages.
For maintainability, I usually mash/minify all of my third-party libraries (such as jQuery, jQuery-UI, Backbone, etc) into a single JS file, along with any plugins for them which I know I will be using throughout the site. The downside to doing this is that you may have one very large JS file which loads the first time the user loads the page - the upside: client-side cache that file, and the user doesn't have to load it again.
The general rule of thumb is: minify the number of bytes that the user has to download, and minify the number of HTTP requests which the user has to make throughout your site. So - by compressing these kinds of files into a single download, and letting it exist on every page with the same URL - you can have a single request which generally gets a 302 response and no download. This is far better than having 5 different plugins which are loaded on different pages, each of which makes a separate HTTP call - even if those calls all receive 302 responses.
It is not a proper Approach to referencing jquery references on Content Page.
Once give jquery references on Master Page and use them on all content Pages. It is, Proper and Optimized approach.
I'm writing a web-app, using javascript, for the first time.
I was wondering what is the best method to make the web-app easily reusable, i.e. to make a "package" containing the js files, html and css, and load them like "load webapp"->launch it.
Currently I have an index.html which contains two divs:
the first one is a site-specific home page
the second one, initially hidden, is the panel of the web-app
once an initial selection is done in the homepage, I launch the app invoking a js method.
I'd like to make this more general, and I was wondering whether using jquery load() could be a clean solution (I'm currently using jquery). This would load the html, but I think I should still manually load the css in the page using the lib/app.
Any idea is appreciated.
Just make sure you don't embed any CSS or JS into your ASPX pages wherever possible, always keep them in separate files it'll be much easier to reuse certain aspects without having to dig around for the code. I've even seen JavaScript classes used to encapsulate a range of functionality, which could also be an option if you're that way inclined :).
In your said example, you're probably best calling a function in an external JS file on document ready.
Organizing your JS as JQuery plugins may also be an option for you. It may not make sense to put all of your JS into one plugin but if you split up your work into bite sized components this may make sense. Im not going to mention any particular resource because there are so many and I don't want to look like a spammer.
Hope this helps!
jQuery load won't help you organize your code, or load js dynamically, it has a complete other function (register to the onLoad event, or load an html page, or partial page via ajax)
If you're looking for dynamically load js libraries, use lab.js (at http://labjs.com) or require.js (at http://requirejs.org). But keep in mind that it can also be ok to have just one big js file that will get cached and load at once.
As far as organizing your js, it depends on the app. Sometimes jQuery plugin is the way to go. I had developed a solution that I am using on my projects, I just share it with you here: http://thebeast.heroku.com
Do you localize your javascript to the page, or have a master "application.js" or similar?
If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages?
EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/paste the jQuery source into their page but you never know.
Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering.
And yes, if one of the js files you are using is also hosted at google, make sure to use that one.
Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do.
All shared JS code lives in the SITE/javascripts directory, but it's loaded in 'tiers'
For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The script tags go at the top of the page.
There's also 'region-wide' stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags)
For less-shared stuff (say my library that's only needed in a few places) then I put a script tag in those HTML pages individually. The script tags go at the top of the page.
For stuff that's only relevant to the single page, I just write inline javascript. I try to keep it as close to it's "target" as possible. For example, if I have some onclick js for a button, the script tag will go below the button.
For inline JS that doesn't have a target (eg: onload events) it goes at the bottom of the page.
So, how does something get into a localised library, or a site-wide library?.
The first time you need it, write it inline
The next time you need it, pull the inline code up to a localised library
If you're referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library
If it's needed from more than one region, pull it up to a site-wide library.
A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view.
However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more 'super' js files for production situations.
I'd recommend using features like this rather than compromising the quality/readability of the actual source code.
Yahoo!'s Exceptional Performance Team has some great performance suggestions for JavaScript. Steve Souders used to be on that team (he's now at Google) and he's written some interesting tools that can help you decide where to put JavaScript.
I try to avoid putting javascript functions on the rendered page. In general, I have an application.js (or root.js) that has generic functionality like menu manipulation. If a given page has specific javascript functionality, I'll create a .js file to handle that code and mimic the dir structure on how to get to that file (also using the same name as the rendered file).
In other words, if the rendered page is in public/dir1/dir2/mypage.html, the js file would be in public/js/dir1/dir2/mypage.js. I've found this style works well for me, especially when doing templating on a site. I build the template engine to "autoload" my resources (css and js) by taking the request path and doing some checking for the css and js equivalents in the css and js directories on the root.
Personally, I try to include several Javascript files, sorted by module (like YUI does). But once in a while, when I'm writing essentially a one-liner, I'll put it on the page.
Best practice is probably to put it on Google's servers.
(Depends what you mean by "your" javascript though I suppose :)
This is something I've been wrestling with, too. I've ended up by using my back-end PHP script to intelligently build a list of required JS files based on the content requested by the user.
By organizing my JS files into a repository that contains multiple files organized by purpose (be they general use, focused for a single page, single section, etc) I can use the chain of events that builds the page on the back-end to selectively choose which JS files get included based on need (see example below).
This is after implementing my web app without giving this aspect of the code enough thought. Now, I should also add that the javascript I use enhances but does not form the foundation of my site. If you're using something like SproutCore or Ext I imagine the solution would be somewhat different.
Here's an example for a PHP-driven website:
If your site is divided into sections and one of those sections is calendar. The user navigates to "index.phhp?module=calendar&action=view". If the PHP code is class-based the routing algorithm instantiates the CalendarModule class which is based on 'Module' and has a virtual method 'getJavascript'. This will return those javascript classes that are required to perform the action 'view' on the 'calendar' module. It can also take into account any other special requirements and return js files for those as well. The rendering code can verify that there are no duplicates of js files when the javascript include list is built for the final page. So the getJavascript method returns an array like this
return array('prototype.js','mycalendar.js');
Note that this, or some form of this, is not a new idea. But it took me some time to think it important enough to go to the trouble.
If it's only a few hundred bytes or less, and doesn't need to be used anywhere else, I would probably inline it. The network overhead for another http request will likely outweigh any performance gains that you get by pulling it out of the page.
If it needs to be used in a few places, I would put the function(s) into a common external file, and call it from an inline script as needed.
If you are targeting an iphone, try to keep anything that you want cached under 25k.
No hard and fast rules really, every approach has pros and cons, would strongly recommend you check out the articles that can be found on yahoo's developer section, so you can make informed decisions on a case by case basis.