Javascript Script manager in a widget environment? - javascript

I'm creating a website that could potentially contain many widgets. These widgets are rendered using external javascript code in external js files. Some of these widgets require the same external javascript files but i obviously dont want the browser including (ie: ) a javascript file whenever a widget requires one; instead it will only include a javascript file when it has not already been retrieved or is in the process of retrieving one.
Is there a javascript manager that can fulfill the requirements above? Extra points will be given to the solution with jQuery in mind :).

I use Google's AJAX API to load jQuery and various other libraries I use.
It cuts down on bandwidth since the user won't get the resource from my server, and also the odds of them having the library are higher.
Here's a link.

Dojo's dojo.require and dojo.provide does exactly what you are asking for. Example:
dojo.require("com.project.widgets.someWidget");
Which would load com/project/widgets/someWidget.js. Inside of that file, you would have
dojo.provide("com.project.widgets.someWidget");
Which registers the source as loaded.
It basically does a synchronous AJAX request, eval's the file, and marks the path as "fetched" so that it doesn't make the same request twice"

Related

Is There any Disadvantages for Using JQuery Load Function?

I am currently developing a web site which basiclly shows the sensor datas. The site must have a chart and I suppose to use HighChart line chart. Because of the website hasn't too much contents, I decided to make all the action one page (graphs, tables...). So this page has lots of parts. To avoid this clutter, I want to build graph part in another HTML file and via JQuery load function, use this in the main page. The only way that I know how to show or use the other codes is this.
For example:
$('.sampleDiv').load('sampleHtmlFile');
And the problem begins. I am not sure whether this way influence the whole page and its well designed structure. Is it bad practice for a developer? Are there any reason to or not to use load function like this way? Maybe another way to handle this problem...
By the way, I am too new for Web Development.
I would not recommend to use jQuery's load to load web-pages that depend on javascript (I assume you want to use http://www.highcharts.com/).
specially as a beginner you will run into a lot problems doing this.
more info:
.load() is nothing else than an ajax call - and you run into problems loading new javascript scripts to the page via ajax.
the browser can't handle loading scripts via ajax by itself correctly so the browser handles the request like it was synchronous and you'll receive this warning:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
to prevent this you'll need something like jQuery.getScript() to load external javascript files with .load().
TL;DR:
I wouldn't recommend to load html files which include external javascript files when you are a beginner. you can get get into a lot of troubles - from missing dependencies into browsers handling the ajax requests like synchronous requests.

Organizing Javascript w/ jQuery

I am tinkering around with jQuery and am finding it very useful and almost exciting.
As of now, I am referencing the jQuery script via Google's CDN and I store plugins I use locally in a static/scripts directory.
Naturally, each page has its own individual implementation of components that are required for the features it currently offers. I.E. the main page has the Twitter plugin whereas the login page has form validation logic and password strength metering. However, certain components (navigation bar) for example use the same script across multiple pages.
Admittedly so, I am not a fan of putting javascript code in the header of a page, but I rather prefer to have it in an external file (for caching, re-usability, and optimization purposes).
My question is, what is the preferred route for organizing the external files. I wanted to try and keep it to one javascript file for the entire site to reduce IO requests. However, I am not sure how to implement document ready functions on a conditional per page bases.
$(document).ready(function () { ... }
Is there some way to reference a page by some method (preferably id based and not a url conditional).
Thank you in advance for your time!
You should try REQUIRE JS.
This will allow you to load only those plugins the pages where you need them, and unload them again if they are not needed anymore.
Then again, it might be overkill. It really depends on the size of your project.
Paul Irish:
http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
This will allow you to block your scripts by body class/ID and execute them automatically.
First you might want to use YUI Compressor or some other JS compressing tool. Then perhaps creating a resource file (resx) for your JavaScript is the way to go. Then just reference the resource within your code. This is the approach Telerik took for their RadControl ASP.NET AJAX control framework.

Javascript and website loading time optimization

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.

Lazy loading and dependency resolution

some time ago, I was reading an article(a library built by some guy) about how his library can do
lazy loading of JS
resolve dependencies between JS
(typically encountered when trying
to "include" one js from another)
include files only once. thought
specified multiple times regardless
of how they are called (either
directly specifying it as file or
specifying it as one of the
dependencies)
I forgot to bookmark it, what a mistake. Can some one point me to something which can do the above. I know DOJO and YUI library have something like this, but I am looking for something which I can use with jQuery
I am probably looking for one more feature as well.
My site has asp.net user controls
(reusable server side code snippets)
which have some JS. Some of them get
fired right away, when the page is
loading which gives a bad user
experience. Yahoo performance
guidelines specify that JS should
be at the bottom of the page, but
this is not possible in my case as
this would require me to separate the
JS and the corresponding server side
control into different files and
maintenance would be difficult. I
definitely can put a jQuery
document.ready() in my user control
JS to make sure that it fires only
after the DOM has loaded, but I am
looking for a simpler solution.
Is there anyway that I could say "begin executing any JS only after DOM has loaded" in a global way than just writing "document.ready" within every user control ?
Microsoft Research proposed a new tool called DOLOTO. It can take care of rewriting & function splitting and enable the on-demand js loading possible.
From the site..
Doloto is a system that analyzes
application workloads and
automatically performs code splitting
of existing large Web 2.0
applications. After being processed by
Doloto, an application will initially
transfer only the portion of code
necessary for application
initialization. The rest of the
application's code is replaced by
short stubs -- their actual function
code is transferred lazily in the
background or, at the latest,
on-demand on first execution.
OK I guess I found the link
[>10 years ago; now they are all broken]
http://ajaxian.com/archives/usingjs-manage-javascript-dependencies
http://www.jondavis.net/techblog/post/2008/04/Javascript-Introducing-Using-%28js%29.aspx
I also found one more, for folks who are interested in lazy loading/dynamic js dependency resolution
http://jsload.net/
About the lazy-loading scripts thingy, most libraries just adds a <script> element inside the HTML pointing to the JS file to be "included" (assynchronously), while others like DOJO, fetches it's dependencies using a XMLHttpRequest and then eval's its contents, making it work synchronously.
I've used the YUI-Loader that is pretty much simple to use and you don't need the whole library to get it working. There are other libraries that gives you just this specific funcionality, but I think YUI's is the safe choice.
About your last question, I don't think there's something like that. You would have to do it yourself, but it would be similar to using document.ready.
i did in my framework a similar thing:
i created a include_js(file); that include the js file only if it isn't included reading and executing it with a synchronous ajax call.
Simply put that code in top of the page that needs dependencies and you're done!

What is the best/fastest way to include my external javascripts? I use jQuery

I am nearly done with my site and am optimising it at the moment; I would like to know the best and fastest way to include all my external javascript files. I want the site to download as quick as possible, but it has quite a few (10 or so) external javascript files that need to be loaded; some are jQuery library files from Google's AJAX API and some are mine.
I'm sure I read a while ago that I could call all external scripts using a bit of javascript code, in effect, only calling one external file from the browsers point of view.
Do you see what I mean?
Many thanks
Combine all your Javascript into one external file (you can do this dynamically and save the cached result);
Minify that file;
Version that file (I use the mtime of a preconfigured file for this);
Gzip the file if the client supports that; and
Use a far futures Expires header on the file.
What you're referring to (using Google's AJAX Libraries service) is another way to handle this that falls under the heading of a CDN (Content Delivery Network). The idea being that the file is stored in multiple plallllces and the client will download the closest (and that result will be saved).
That's hard or just awkward to combine with other techniques and I've found that doing multiple external loads this way completely erodes any perceived benefit (unless that's your only external load) so I use the method listed above instead.
My guess is to combine the library files to just one file (except the ones hosted at Google). Each call to your server takes quite some resources, so you're better off with just one call. You can even combine the files online:
http://yui.2clics.net/
I would suggest merging all the scripts together into one JS file, and then using the YUI Compressor to pack them into a smaller file.
To use scripts browser has to download them anyway so I don't think there is any difference how do you call them... unless you use compressing on server and decompressing on client side.

Categories

Resources