including javascript files in my page - javascript

I have many (almost 15) javascript files which I am using in my webpage.
What is the best way to include all of these files?
Simply at bottom or is there some other technique that should be used which can load javascript faster?

You could combine and minify them. YUI Compressor could do that.

You may consider using a parallel/non-blocking javascript loader.
Following are some great libraries that could do this for you..
http://headjs.com/
http://requirejs.org/
http://labjs.com/

Google Closure Compiler has a convient web api for merging and minifying all your js.
https://developers.google.com/closure/compiler/docs/api-ref
You can put a script tag with a direct link to the api.

I haven't quite mastered implementing all this yet I have found that a fair amount of minification & concatenation can be automated by servers, I have learned a fair amount from reading the (well-commented) .htaccess file in the HTML5 Boilerplate and associated docs.
Modernizr also features an asyncronous loader function and it was well enough documented that I was able to get it to work when I just couldn't quite figure out require.js

You could use a script loader library or you can do it yourself.
Where to include scripts and how the browser loads resources
Always at the bottom just before the closing <body> tag, to enhance the user experience. It ensures that the page content gets rendered first, which gives the impression that your pages load quicker.
The browser runs a single thread and will process the page content from top to bottom, if it happens on a resource, it first has to retrieve the resource, process it and then only continue with the next tag on the page. Since we generally want to wait for the DOM to be finished loading, before running any scripts in any case, this strategy is always a win win.
Size matters
For production you want to ensure that all your scripts are minified regardless of the strategy you are going to employ to get them loaded (smaller size == less to download == quicker)
The correct order
Most important is always the dependency order, if we call a function or access a variable and the browser doesn't know about it first, the script will fail. You want to ensure that a script is only included after any scripts they depend on. So the first thing to do is to work out the order by which you need to include and introduce functionality to the browser.
How to include scripts into a page
There is only one way to include a script in a page (not recommending same origin ajax/eval) and that is by means of the <script> tag.
There are only 2 ways to create a <script> tag:
Statically located in html or
dynamically added with JavaScript.
Statically added scripts
Since we know the order we need our scripts included we can add them one by one after each other like this
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.5.2/jquery.tablesorter.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.5.2/jquery.tablesorter.widgets.min.js"></script>
Dynamically added scripts
There are three ways to effectively create script tags in the dom, dynamically, which we will explore. These are certainly not the only ways...
document.write
The write method will append to the existing dom.
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>');
But now we have a problem as there is no way of telling that the script is done loading, because we have to wait until it is complete before loading the next one or calling something that is defined there.
document.createElement
The createElement method creates a dom element and we can insert it anywhere in the dom we choose.
The following example checks if jQuery exists or creates a <script> element to go fetch it. In any event, the function ready_go is called and we should have jQuery.
(function() {
if (!window.jQuery) {
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.async = true;
jq.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(jq, s);
jq.onreadystatechange = jq.onload = ready_go;
} else ready_go();
})();
jQuery.getScript
Since we have jQuery now we don't have to do things the hard way, getScript takes as first argument the script url and will call the function as 2nd argument once the script is complete.
function ready_go() {
$.getScript('http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.5.2/jquery.tablesorter.min.js', function () {
// script is done loading we can include the next
$.getScript('http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.5.2/jquery.tablesorter.widgets.min.js', function () {
// script is done loading we can include the next or start using our stuff
});
});
}
Where to get the scripts from?
You either want to get the scripts from public CDN or host them yourself. An important concept to bear in mind is that scripts, as with any other resources get cached by the browser and you will not be required to repeatedly download the same scripts.
Scripts from a Content Delivery Network
The advantage of a CDN is twofold;
you get closer to the user, because a CDN consists of POPs distributed across the world and even though you are calling one url the server responding may be different
many sites may use the same CDN if your user already got jQuery from google's CDN when visiting my site his browser will simply use the cache copy already in its possession when requested by you.
Scripts served from origin (your server)
I agree with the strategy that #Mario and #Xharze suggests, beats including 18 scripts on every page.
Use CDNs where scripts are available but for the rest.
Concatenate all your scripts together, keeping in mind that the same dependency order applies, and minify them.
Having one script will simplify your includes and because the browser will cache the script no additional downloads will be required again, especially beneficial in application used for extended periods and accessing many pages.
The only advantage separate scripts hold is for users who exit from the landing page and why do we care to optimise for them they're not going to stay because of it.
nJoy!

Related

Loading Coldfusion javascript asynchronously?

Whenever a page is loaded with Coldfusion, it loads many default Coldfusion javascripts. When I run the Goolge PageSpeed Tools, it always complain about the render-blocking JavaScript. Apparently, Coldfusion has many javascript when a page is loaded such as
...scripts/ajax/yui/yahoo-dom-event/yahoo-dom-event.js
...scripts/ajax/yui/aniax/yui/autocomplete/autocomplete-min.js
...scripts/ajax/yui/autocomplete/autocomplete-min.js
...scripts/ajax/messages/cfmessage.js
...scripts/ajax/package/cfajax.js
...scripts/ajax/package/cfautosuggest.js
...scripts/cfform.js
...scripts/masks.js
These all are considered render-blocking scripts. I can't find any information on how to make them none-render-blocking because obviously I can't add the async="async" parameter to the Coldfusion script which I can't see. How can I make the Coldfusion script none-render-blocking or am I stuck with it?
Can someone please shed some lights?
If you really wanted to do something about this instead of rewriting your UI code, you can actually grab the output from the buffer before it is sent to the client and modify it. Your modifications could be as simple as removing a hardcoded list of script tags and replacing them with a custom script file that you host in your webroot. The custom script file would simply be all of the other script files' contents combined.
To do this:
In onRequestEnd in application.cfc you can call var outputBuffer = getPageContext().popBody().getBuffer() which will return the body to be sent to the client.
Run replacements on outputBuffer, looking for those script tags and removing them via regular expressions. You'll want to keep track of whether or not you've actually removed any to use as a flag in the next step.
Finally, you would append to the output with your new master script tag if your flag that replacements have been made is true. After you do that, the buffer will be automatically flushed to the client.
I believe that Adobe no longer updates the script files, so you basically don't have to worry about versioning your master script file to clear the browser cache.
Edit/Note: Definitely avoid using the CF UI stuff, but we don't know what your situation is like right now. If you have hundreds or thousands of hours of rewriting to do, then obviously rewriting it all is likely not something that is practical at this time.

Difference in performance and memory footprint between referencing a Javascript using src or directly injecting it in the HEAD

What are the differences in performance and memory footprint , if any, in these different approaches:
1. Using Src
<script type='text/javascript" src="1MBOfjavascript.js"></script>
2. Directly injecting in the Head
$('head').append("<script type='text/javascript'>1MBOfJavascriptCode</script>");
I'm interested because we are developing a Cordova App where we use the second method to Inject to the DOM a previously downloaded Javascript bundle read from the HTML Local Storage.
Given that the script will probably grow in size, I'd like to know if with the second method I could incur in some memory issues or other DOM problem.
I believe the overhead in such cases should be insignificant as the main processing/memory consumption is based on how the actual script works. Ie the memory used by file would be the total size of the script which is what 1MB at max? However during execution the same script can use up 100MB easily.
Anyways , coming to the point.
Plain text inclusion would be better if it has to be included in all cases as it skips a script execution and also does not cause re-rendering by browser after the append.
Append option should be used in cases where you only need the script under specific conditions on client side and do not load it un-necessarily.
The browser goes through all elements before to render the page so I would imagine it is exactly the same, if anything if you had scripts after the page is downloaded chances are that you will get errors of the type "call to undefined functions" if you call onto a function that you have added after the load.
My advise would be add them at load using src but keep things tidy.
Javascript impact a lot depending upon how and where you are loading your file, there are many ways to load a file or code.
First method you mentioned is an conventional way to load javascipt file that is load file using src and usually its loaded before closing </head> tag but now a days it is in trend to load file befor your </body> tag. it speeds up application load and prepare DOM faster.
second method is not obviously a good way to load javascript at first as there can be some code that should be working only after your DOM is ready and as here you are loading your javscript with javascript/jquery append which depends upon your jquery file loading which will delay your code execution. and there might be possible that some of your code will not have desired output (depending upon how you have called functions and how much they are dependent upon DOM ready )
I would prefer to load a javascript file with first method and at the bottom of the page/app if possible.
asyncrounous loading can also be tried.
i think because browser behavior after retrieving response from any web server
will try to parse all the elements first for building the DOm, after the DOM are ready then your script would be executed, based on this it is obvious its the main
reasons is which is the first
will be executed first than injecting it.
About the second method
i think javascript engine in each browser can handle that thing easily and withouth any problem. the engine does not care about the size actually it only about how long the script will be loaded and then executed. what will be the issue is when you try injecting any elements into DOM is when you try to do it in loop there might be a memory problem.
when you say big javascript files yeah we should think about the memory. but
about the method you previously said its just about which are executed first.
thats my opinion

AJAX ready event once HTML page and scripts are loaded

I'm creating a web application that has multiple pages of content that I'm loading dynamically with AJAX and the HTML5 History API. When a user attempts to change the page, the new content is loaded with a $.get and injected into the body, like so:
$.get("somepage.html", function (data)
{
$("body").html(data);
});
Most of these pages require additional scripts to be loaded. This wouldn't be an issue except for the fact that $(document).ready fires before these scripts are loaded. Somepage.html looks something like this.
<script src='http://getjquerysomewhere/'></script>
<script src='my_script_that_depends_on_jQuery'></script>
This issue is complicated by the fact that these pages must have the ability to be loaded on their own. I'm therefore unsure how I can eliminate the $(document).ready functions without affecting this behavior as well.
How should I approach this problem?
What you are trying to do is certainly possible, but it's not going to be very maintainable in the long-run.
One of the biggest issues you'll run into is properly injecting the code from the ajax loaded html into the current page. You can't just ignore it and let it all run because then you'll be including libraries multiple times (resulting in plugins getting overwritten/removed), and the code for the page you are loading may happen too soon due to the dom already being ready.
This pretty much leaves you with two options: dependency injection or front-loading.
Dependency injection will probably be the easiest of the two for you to implement because it requires the least amount of changes to your current code-base. All you would have to do is ensure that all pages requested with ajax only include the content of the <body> (which can be done with server-side code), and ensure that all page-specific code is included before the closing </body> of each page. Then you would just have to use the dependency-injection methods to run your code with the proper dependencies.
You could also have it only include <div id="#content">...</div> for your partials, which ever makes more sense for your use-case.
Front-loading would be a little more difficult because you'll have this one giant file that has all of your code for all of the pages, unless you use a build process (if you've never used a build-process before, you really should try it, even if you don't think you need it.) With front-loading, you'll either have to use event delegation, or have init methods for each page that you selectively execute as you load each page. This could become a maintainability nightmare without good build processes.
You can call functions from the original scripts on the page which you have loaded. For Instance you could do this in your main:
<script>
function ExternalScriptLoaded(){}
</script>
Then on your external page:
<script>
try{ ExternalScriptLoaded(); }catch(err){alert('This page was not loaded with ajax because i can't find the function');}
</script>
The alert will trigger if the script can't find the function on your main page.
i.e. call the function after you know the script has finished runnng.
Hope this helped.

How to handle dependencies when libraries are loaded asynchronously?

Google Pagespeed said I should load my JS files asynchronously, but this has introduced a problem for many of my pages with code using libraries and plugins.
For example, I have the following code on one page:
$(document).ready(function () {
var hound = new Bloodhound({ .......
});
So when the page loads, I am creating a Twitter Bloodhound (goes with Typeahead) object. The problem is, if Bloodhound and Typeahead are loaded asynchronously, then an error is thrown:
Uncaught ReferenceError: Bloodhound is not defined
This is because those scripts haven't been loaded yet.
I came up with this solution:
$(document).ready(function () {
createBloodhound();
});
function createBloodhound() {
if (typeof Bloodhound != "undefined") { // if bloodhound JS has loaded
var hound = new Bloodhound({ .......
}
else {
setTimeout(function(){
createBloodhound();
}, 10);
}
}
Is this a good practice, or is there a better way?
NOTE: I realize there are libraries like RequireJS out there to handle dependencies when loading files, but I don't think this type of solution will not work in my case because I load the libraries asynchronously in a wrapper file (since they're required for every page). The example code here would not be on every page, but only on a specific page on my website.
The best approach is to use a callback mechanism, which you can react to, rather than using a polling mechanism. I used script.js, which is simple and yet functional, and offers the callback mechanism.
Without that, you could implement something yourself. Performance-wise though, utilizing callback are better.
Depending on the complexity of your site, different options might be best. If...
All of your javascript is in JS files
Your above-the-fold content looks identical before and after the JS is loaded (or close enough to identical that the flash of change when your JS does load wouldn't distract your users)
The total file size is small (or most of your JS is needed on pages everyone will visit every time they visit your site)
... then combine them into one file and just server that instead of all the individual ones. Then you don't have to worry about dependencies at all. Include that script file at the bottom of your body tag (no need for async or defer attributes, but you can use them if you want).
If some of your javascript is necessary to make your above-the-fold content look correct, do the same thing, except split your JS into two files. One file contains only what is necessary to make the above-the-fold content look correct, and the other file contains everything else. Include the first one in your head tag (possibly inlining it), and include the second one at the bottom of your body tag. If the second one depends on the first tag, do not use the async attribute, because it might get executed first.
If you have some large JS files that are only used on some pages, and those files depend on other JS files, stick your scripts at the bottom of your body tag and use the defer attribute.
If you have javascript mixed in with your HTML, you can use a callback mechanism (like script.js), or you can build up execution queues like Google Analytics does, which the external script knows to look for when it first loads.

Where to put JavaScript configuration functions?

What is the general developer opinion on including javascript code on the file instead of including it on the script tag.
So we all agree that jquery needs to be included with a script file, like below:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>
My question is, in order to get functions on a page that is not on all pages of a site. Do we include the functions like below in the same page or in a global include file like above called mysite.js.
$(document).ready(function(){
$(".clickme").click(function(event){
alert("Thanks for visiting!");
});
});
ok. So the question is: if the code above is going to be called in every class="clickme" on a specific pages, and you have the ability to call it either from an include separate file called mysite.js or in the content of the page. Which way will you go?
Arguments are:
If you include it on the page you will only call it from those specific pages that the js functionality is needed.
Or you include it as a file, which the browser cached, but then jquery will have to spend x ms to know that that function is not trigger on a page without "clickme" class in it.
EDIT 1:
Ok. One point that I want to make sure people address is what is the effect of having the document.ready function called things that does not exist in the page, will that trigger any type of delay on the browser? Is that a significant impact?
First of all - $("#clickme") will find the id="clickme" not class="clickme". You'd want $(".clickme") if you were looking for classes.
I (try to) never put any actual JavaScript code inside my XHTML documents, unless I'm working on testing something on a page quickly. I always link to an external JS file to load the functionality I want. Browsers without JS (like web crawlers) will not load these files, and it makes your code look much cleaner to the "view source".
If I need a bit of functionality only on one page - it sometimes gets its own include file. It all depends on how much functionality / slow selectors it uses. Just because you put your JS in an external JS file doesn't mean you need to include it on every page.
The main reason I use this practice - if I need to change some JavaScript code, it will all be in the same place, and change site wide.
As far as the question about performance goes- Some selectors take a lot of time, but most of them (especially those that deal with ID) are very quick. Searching for a selector that doesn't exist is a waste of time, but when you put that up against the wasted time of a second script HTTP request (which blocks the DOM from being ready btw), searching for an empty selector will generally win as being the lesser of the two evils. jQuery 1.3 Performace Notes and SlickSpeed will hopefully help you decide on how many MS you really are losing to searching for a class.
I tend to use an external file so if a change is needed it is done in one place for all pages, rather than x changes on x pages.
Also if you leave the project and someone else has to take over, it can be a massive pain to dig around the project trying to find some inline js.
My personal preference is
completely global functions, plugins and utilities - in a separate JavaScript file and referenced in each page (much like the jQuery file)
specific page functionality - in a separate JavaScript file and only referenced in the page it is needed for
Remember that you can also minify and gzip the files too.
I'm a firm believer of Unobtrusive JavaScript and therefore try to avoid having any JavaScript code in with the markup, even if the JavaScript is in it's own script block.
I agreed to never have code in your HTML page. In ASP.net I programmatically have added a check for each page to see if it has a same name javascript file.
Eg. MyPage.aspx will look for a MyPage.aspx.js
For my MVC master page I have this code to add a javascript link:
// Add Each page's javascript file
if (Page.ViewContext.View is WebFormView)
{
WebFormView view = Page.ViewContext.View as WebFormView;
string shortUrl = view.ViewPath + ".js";
if (File.Exists(Server.MapPath(shortUrl)))
{
_clientScriptIncludes["PageJavascript"] = Page.ResolveUrl(shortUrl);
}
}
This works well because:
It is automagically included in my files
The .js file lives alongside the page itself
Sorry if this doesn't apply to your language/coding style.

Categories

Resources