Increasing page load time - javascript

I have a javascript source code file which is about 32kb, and has javascript code arranged in modules.
I was wondering if it would increase page load time if i put each module into a separate file as managing the current code of over 2000 lines is quite tedious and some times confusing

Short answer, yes and no. If you have a <script> tag pointing to each module file, then yes it will slow down the page due to the increased number of network calls to those files. The real answer is that's the way you should CODE it, but that's not the way you should serve it up to your user.
I recommend a tool called Minify, which will combine and minify all your JS files so you only need one <script src="/min/f=mod1.js,mod2.js,mod3.js" type="text/javascript"></script> tag
You can also manage "groups" of files, which are simply PHP arrays with an associative key you reference in the script src. For example:
'module_js' => array(
'//js/module1.js',
'//js/module2.js',
'//js/module3.js'
)
Then your script tag would look like:
<script src="/min/g=module_js" type="text/javascript"></script>
After Minify comines and minifies your code, it will cache it on your server so subsequent requests will hit the cache file so the PHP won't need to process.
http://code.google.com/p/minify/

Related

Having multiple css and javascript files

I have multiple jquery, javascript and css files loading in my head. I want a way to simplify and fasten up the process of loading these files. I also have different javascripts in the head and above the /body tag. I have looked into requirejs and headjs but I find it very complicated and don't know if I can load my stylesheets with this framework.
The size of the site is quite large due to it being a scroll to section site. My question is, is there a way to load my css, javascript files, jquery code and javascript in a simple fast way and if this is possible with headjs or requirejs can someone give me an example on how to do this in an easy way as I am just so confused as their API is not easy to follow for beginners.
Thanks.
The simplest first step you can take is to reduce the number of HTTP requests. Typically, each request spends as much time queued as it does downloading, so you can reduce all of the queue time by having a single CSS file and a single JavaScript file.
So your first step is to combine the files in the same order you include them and then include just the one combined CSS file and the one combined JavaScript file.
Next Steps
Once you've done this, you can follow it up with:
Minification. This is a process that makes your file size smaller, for example by removing unnecessary white-space and by compressing variable names.
Move script includes to just before </body>. This gives the illusion of speed as the visible page will load before the script is requested, which makes the page appear faster to the user.
To easily merge CSS :
Make a php file,
<?php
header('Content-type: text/css');
header("Vary: Accept-Encoding");
header("Cache-control: public");
header("Last-Modified: ".gmdate("D, d M Y H:i:s"). " GMT");
$cssstyles = '';
$lines = file("file1.css");
foreach ($lines as $line_num => $line)
$cssstyles .= trim($line);
$lines = file("file2.css");
foreach ($lines as $line_num => $line)
$cssstyles .= trim($line);
$lines = file("file3.css");
foreach ($lines as $line_num => $line)
$cssstyles .= trim($line);
echo preg_replace('/\/\*(.+?)\*\/|[\s]*([:;{},>])[\s]*/','$2',$cssstyles);
?>
Replace file1, file2, file3 by each of your files.. You can pass a GET parameter to get different CSS for different pages.
And then call your file as stylesheet with :
<link rel="stylesheet" href="yourFile.php" />
You can use js/css combine techniques to reduce requests from server
https://code.google.com/p/minify/
There are other ways as well like host external files on other server. (CDN technique)
This will also help you:
http://sixrevisions.com/web-development/site-speed-performance/
You can try to compress/minify it and merge it together.
Javascript: Google CLosure Compiler (online)
or minify: Minify
There are thing that you can do for a better performance like:
Merge you small CSS or JS files to one file to reduce number of requests.
Use GZip on your server to reduce size of your resources. (for example jQuery minified version is about 90kb but after enabling GZip on your webserver it will become 30k)
Setting up GZip for your server is vwery simple.
Use tools that will minify your codes. You can save up a lot after minification your code. there are many online tools like this one which I always use.
It's a while that I put my javascript codes at the end of my page right before closing body tag. You may not be able to run jQuery code for example in middle of your HTML but the advantages of loading JS at the end are more than this one disadvantage.
Have a look at these articles.You need to learn the optimization technique to increase the efficiency of code loading.
load-javascript-faster
faster-page-loads-bundle-your-css-and-javascript
speed-up-your-javascript-load-time
One of the best things you can do is minify your files that you put live. There are various free services that do this, such as http://gruntjs.com or http://jsmini.com
A step further, if your site uses PHP, then you can setup some files to load conditionally.
On my personal sites... I use PHP to set the variable $title equal to whatever the simplified page name is, for example "home" or "gallery".
I then include two files into my <head> one for conditional CSS files, and one for conditional JS files...
Then I for example there are 3 javascript files and two css files that are ONLY needed for the gallery page. So I have a simple IF statement in the two conditional files mentioned above like this:
if ($title == "Gallery") {
echo "<script src=\"afile.js\"></script>";
}
This way, these particular files never get loaded unless they are actually required. There are ofcourse certain CSS sheets and javascript files which are required site-wide, in which case I enter those into the <head> just like you would normally, and I always load my "conditional files" BELOW their respective counterparts.
I believe that what you are looking for is called bundling and minification. You can use it to conacatenate all javascript files in one big file, and also minimize its size. The same thing apply to css files.
There are a lot of different solutions depending on the platform that you are using for developement.
For example:
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
You can reduce the size of your webpage by following two things
1)Compress your Files :
Genrally js/Css files are written with lots of white spaces for readability and thus they occupy more bandwith. After Compression you can generally gain 30-50% reduction in the size of Javascript files and 40-70% reduction in Css files.
2)Combine more than one files:
Each time a file is sent from server to client it occupies request response headers and some other informations. This can be reduced by combining files.
In case of related files of javascript and css files you can combine multiple js/css files in one files.
you can use online tools which compresses as well as join multiple css/js files into one
like
jsCompressor and CSS Compressor

Calling functions from js file to html page

I have three js files for all of my webpages, and I have pre-defined sets of functions to call for each web page. Could I move all of these functions to a new js file which would make then calls to other functions in a different js file? I read about rloader at http://code.google.com/p/rloader/, but I am not sure if I could use it.
<script src="js/rootNameSpace.js"></script>
<script src="js/jquery-min.js"></script>
<script src="js/ui.js"></script>
<script src="js/form.js"></script>
<script type="text/javascript">
console.dir(com);
com.rela.form.helloWorld1();
com.rela.form.helloWorld2();
</script>
Yes. If you move the contents of the script tag to a file with the path "js/main.js" and then added a script
<script src="js/main.js"></script>
after the other scripts, it will be able to call the functions. Including an external script is equivalent to having the text from that script inline in the file.
Scripts can read the contents of previous scripts so having multiple scripts on the page is similar to concatenating them all into a single file, which means that if you add a script below the other scripts it will be able to "see" everything in the others
With regard to questions about rloader
rloader does lazy loading to pull in scripts when you need them.
For more on lazy loading
And you can learn about rloader from its site (I'm no expert on that)
For what its worth I would not recommend using rloader if you really only have 4 scripts on one page. Its overkill. If you're planning on having a much bigger project, then you can use it or the more popular requirejs to manage your scripts across pages.
If you have dynamic generated pages you can have different names/actions/controllers whatever.
Then you can
echo '<script type="text/javascript">$(document).ready(function(){'.$page_name.'();});</script>';
Then you can declare global functions in any JS file, yes you can have any number of JS files, and splited in any way you want, they are all global.
function name1(){...};
If you have a big application with many JS files you can split then into more files, in a single folder, then add a minify plugin to "collect" them in a single output file (or a JS builder).
rloader is a dynamic loading script, basically Injects JS files in your document (http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html). I don't recommend using it, except if you have a very big application and use a MVC http://coding.smashingmagazine.com/2012/07/27/journey-through-the-javascript-mvc-jungle/ that loads only the current module.
It is always better to put code in separate files (as far as they are less in size and count). This will allow to be cached by browser $(document).ready will keep you safe for other dom elements that are not loaded.
Create something like this:
<script src="js/rootNameSpace.js"></script>
<script src="js/jquery-min.js"></script>
<script src="js/ui.js"></script>
<script src="js/form.js"></script>
<script src="js/pages/some-page.js"></script>
some-page.js
$(document).ready(function(){
console.dir(com);
//call to function form.helloWorld1
com.relais.form.helloWorld1();
com.relais.form.helloWorld2();
});
A better option would be combine files (If they are common on each page). rootNameSpace.js, jquery-min.js, ui.js, form.js into a file say common.js. You can use Google Closure to do that.
<script src="js/common.js"></script>
<script src="js/pages/some-page.js"></script>

Multiple sources for a javascript file

I am working on a project where I need to include somewhat around 10-15 .js files in the HTML head section directly like
<script type="text/javascript" src="http://localhost:9020/website1/wa/min/soundmanager2.js,vars.js,utils/md5.js,utils/utils.js></script>
what is the way I can give refrences correctly
the files I need to refre are in the same hierarchy like
1.....2,3
2.........4,5
3........6,7
I need to refer 1,4,7 please help.
somewhere I read this method what's it?
<script type="text/javascript" src="http://localhost:9020/wordplus/root/child/?b=scripts&f=soundmanager2.js,vars.js,utils/md5.js,utils/utils.js></script>
The example you posted looks exactly like the query string interface for the minify PHP library: http://github.com/mrclay/minify
Using it you use it in the fashion <script src="min/?b=path&f=script1.js,script2.js,ui/script3.js"></script>.
Where path is the path from your web root that you want it to look for scripts under.
I've used it before and I've found it quite effective. It concatenates, minifies, caches, and serves JS and CSS.
I'm sure there are other libraries to achieve the same effect, alternatively you can create a build script to concatenate and minify all your scripts and then deploy a single JS file to your site, in a single script tag.
It is not possible to load multiple javascript files in a single <script> element.
You have to have to have an individual <script> element for each script you are referencing..
<script type="text/javascript"
src="http://localhost:9020/wordplus/root/child/?b=scripts&f=soundmanager2.js"></script>
<script type="text/javascript"
src="http://localhost:9020/wordplus/root/child/?b=scripts&f=vars.js"></script>
I think you'll get what you need from dynamically loading external javascript files:
http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
The second line you posted requests scripts from the server dynamically. the b parameter of the request tells it you want scripts and the f parameter tells the server which files you want. Then it concatenates these into one file and sends that back to the user agent. You need server-side scripting to handle this; it is not something built into the URL specification.
http://localhost:9020/wordplus/root/child/
b=scripts
f=soundmanager2.js,vars.js,utils/md5.js,utils/utils.js
The simplest solution is just have one script tag per file as it will let you take advantage of caching:
<script src="http://localhost:9020/wordplus/root/child/soundmanager2.js"></script>
<script src="http://localhost:9020/wordplus/root/child/vars.js"></script>
<script src="http://localhost:9020/wordplus/root/child/utils/md5.js"></script>
<script src="http://localhost:9020/wordplus/root/child/utils/utils.js"></script>
Another solution is to use some JavaScript builder to join all your files, generating just one. The pros of this approach is that your result file will be "compressed" (minified). Some builders:
Google Closure Compiler (I like and use this since 2009).
YUI Compressor

One JavaScript File Per Page or Combine when using Jquery and Document Ready Function

Ok So I know it always depends on the situation but I have, thus far, combined my jquery files/plugins into a single compressed file.
Now I am wondering what I should do with my page specific js/jQuery code. Should I have a single file with one Document.Ready function and my entires sites js code inside of it? Or split it up into seperate js files per page with a document ready call in each?
These files will inclide things such as .Click handlers and other jquery code specific to certain pages.
Whats the best practice here to optimize load times and maintainabilty?
One way to do it would be to use require.js and then have an array with files and page types. Give each body tag an ID and use it to reference what files should be loaded in.
<body id="pageName">
Keep your global files everything you need for the core functionality to work and then lazy load in the features that aren't required for your site to run faster. I've seen huge speed improvements from this technique.
http://requirejs.org/
We can do this in multiple ways , i did in the following way.
Aggregate your files broadylyas following
1) Aggregate all the files required for all the pages
2) aggregate the pages specific to the page.
Include all the common aggregated file for all the pages , and include other aggregated files conditionally on the page
1) jquery and other plugins common to all pages so // it will go to all files
2) homepage-aggregation /// for homepage
3) gallerypage-aggregation // for gallery page.
If you include the same file for all the pages ,it may not necessary for all the files.
I did it recently , let me know if you need anything else
Because you're almost certain to want to have different things executed in the Document.Ready function depending on what page you're on I don't think that having one function that is executed on every page is helpful.
Personally I mix my $.ready calls in with my HTML. These are simple calls to functions stored in a single, minimizing javascript file so don't take up too many bytes, and prevent the need for a separate Javascript file per page. It also allows me to initiate the Javascript where I create the markup, so it's all in one place.
If you're minimizing your javascript and serving it with the correct headers you've got most of the benefits already, don't compromise readability more than you have to.
It also depends on the server side technology you are using. You may find tools to assist you on this task. If you are coding a Java server side, you may try JAWR. It allows the creation of separated JS/CSS files, merging and compressing them server-side, turning all the separate files into a single file.
About Document.Ready, I prefer to keep specific code page in separate files, avoiding incorrect code execution and behavior. It is also cleaner and easier to maintain.

Javascript - To combine or not combine, that is the question

Ok, so I know that it's obvious to combine all of a pages Javascript into a single external file for efficiency purposes, but that's not quite the question here.
Say I have Default.htm with a search field that has a little Javascript magic attached to it. Then I have Contact.htm with a contact form that has some Javascript magic attached to it. And finally I have a FAQ.htm with some jQuery panels showing the answers... you get the picture.
Basically I have three pages that all have "some" javascript need, but none of the Javascript is used on any other pages.
Is it better to combine all of that Javascript into one big minified file that loads once and is then stored in Cache, or is it better to use an individual Javascript file on the Default page, but not use it on the Contact page... etc?
What works best in this scenario?
Option: 1
Default.htm
jquery.js
default.js
Contact.htm
jquery.js
contact.js
Faq.htm
jquery.js
faq.js
Option: 2
Default.htm
jquery-default-contact-faq-min.js
Contact.htm
jquery-default-contact-faq-min.js
Faq.htm
jquery-default-contact-faq-min.js
PS: for all you asp.net guys, I'm using Combres to Combine, Minify, and Version my Javascript files
I would definitely vote to combine them. If you are concerned about parse or setup time for the "not used" Javascript, then I would recommend structuring your Javascript with each file in a closure, and then run the closures you need on the pages you need them. For example:
// File 1
window.closures = window.closures || {}
window.closures["page1"] = (function() {
// Javascript for Page 1
});
// File 2
window.closures = window.closures || {}
window.closures["page2"] = (function() {
// Javascript for Page 2
});
// File 3
window.closures = window.closures || {}
window.closures["page2"] = (function() {
// Javascript for Page 2
});
Then, in your page:
<!-- This one combined.js file will be downloaded once and cached //-->
<script type="text/javascript" src="combined.js"></script>
<script>
// Run the Javascript in your combined.js intended for page2
window.closures["page2"]()
</script>
combine into 1 file. let it get cached. it loads once on any page, and for any subsequent pages it can use the cached copy.
Because it doesn't sound like there's a lot of javascript, combining it into one file would be better. Only if there's significant amounts of javascript that doesn't need to be loaded if a user doesn't visit a page then you would consider keeping the files separate.
It is always an act of balancing the number of HTTP requests and limiting the transferred bytes that are not really needed yet.
There are three possibilities:
combine everything in 1 file
have three separate files, and load them as needed
have three separate files, load the one needed for that page right away and preload the others (when the time is right)
You will only know what is best for your situation by doing some A-B load testing.
Everything depends on the size of the transferred data, the overlap of needed functionality and the probability that some functionality is needed.
If the combined file is under say, 25kb minified, then go for it. But if it is more than that, I'd say, identify the one that is the biggest of them, and let that one js file be separate. Combine the rest. That 25kb limit thingy too is not a hard rule, it is up to you.
If your individual files are in the magnitude of say, 30kb, I'd recommend not combining them, and letting the individual js files be cached as individual js files.
Hope that helps.

Categories

Resources