I'm using the Invasion Of The Body Switchers script (http://www.brothercake.com/site/resources/scripts/iotbs/) as a styleswitcher. This requires loading three js files in the header.
I'm trying to reduce HTTP requests by combining scripts when possible. Has anybody used IOTBS before and successfully combined the scripts into one file? Would I need to make any modifications to the scripts or to the HTML switchers on the page to make that work?
The first thing you want to pay attention to is the global namespace. IOTBS uses one global variable: switcher. Since these files are working together, then it is safe to consolidate them into one file. When you're consolidating them, please add them to the file in the order that they are called on the page.
And kudos for deciding to reduce HTTP requests. You're making the Internet a faster place.
If you can put the three scripts into your HTML header in a row and it all loads properly, then you should be able to just concatenate the files together and load them with one script tag.
Separate script tags in HTML does not imply separate namespaces for the code inside.
Related
If you have a lot of files, would there be any benefit to doing something like this in the header:
<style type="text/css">
<?php
include("css/myCss1.css");
include("css/myCss2.css");
include("css/myCss3.css");
include("css/myCss4.css");
include("css/myCss5.css");
?>
</style>
That way server returns one file instead of several. You can also load the content from js in between script tags.
Please don't flame, just explain why this would or would not make sense in a situation where you need to have a lot of individual files and you want to consolidate instead of having the main file make calls for those files individually.
I've tried and they seem to work... but what are the repercussions on the server or benefits of speed (if any).
Just curious... Thank you very much.
UPDATE: Thank you for all replies... Would another solution (that would deal with the cache issue) be to have 1 external php file that load all the other css into it - sort of combining all into 1?? Does that make sense?
You should use an external stylesheet, so it can be cached separately because in most cases PHP is used for dynamic data retrieved from databases and you might not want to cache all the data. If you are not using PHP for anything else than merging CSS, you should definitely use LESS # http://www.lesscss.org, as it is a CSS preprocessing language that has many features that make developing CSS easier which includes merging css files together. You could also try SASS # http://sass-lang.com/ which is similar. This way you reduce the number of HTTP requests, the server doesn't have to keep running PHP code unnecessarily, and don't do as many reads from disk.
Of course that would work, but since the size of HTML output content remains the same and same number of KiloBytes are sent to the client, there is no real benefit here.
And there could be many downsides, first up it would be hard to debug which file to update when you have to update any css class. You'll have to find that manually.
But one major point against this would be that PHP includes are not meant for CSS includes. Although that might appear to work for you, a source code include is for source code. Its bad programming practice and also it requires PHP to parse all those CSS files unnecessarily. This unwarranted parsing of your CSS files will counter the benefits you will obtain by that. Rather you can simply merge all those CSS files together into one.
In addition to Hanky Panky's answer, when including CSS files with HTML code, browsers may cache the CSS file locally, making less data be transferred between the server and the client.
When including the CSS with PHP like in your question, there can be no such local caching of the CSS.
Edit: Using one single PHP for all the CSS could in theory only work if you include the PHP-CSS as a stylesheet using HTML-code. Writing <style type="text/css"> in either the PHP-CSS file or using include inside such statement in your main file would not help. However, either way it is not something that I would recommend. PHP is not for including many CSS-files into one.
I am building a front-end UI framework for developers in my firm to use to build internal web apps. It consists of customized Bootstrap, jQuery, other open-source libraries, internal modules and stylesheets. The user environment is entirely IE9 and my server is .NET 3.5. I am hosting the shared files. Dev teams in the firm will place the links in their project pages and apply the framework to their pages.
I want to offer them the simplest method of implementing this which would be one line of code to paste that builds the library for them. Cutting and pasting 30 lines of code is stale the moment Ctrl + V is pressed, it leaves me no control and is simply inelegant.
Failed Experiments
I tried using Head.js and LazyLoad both of which use best practices for inserting scripts. But each of them has caused either content to display before styled or conditions where methods are called before scripts load. I am giving up on this approach.
It's too volatile.
A simple document.write() solution
Over the weekend, I thought: Why don't I just make a js file named "framework,js", add the script and link files in order with a stack of document.write() lines. Tell developers to put it in the head and that's it. Heck I could add the necessary metatags for IE9 and mobile too for that matter. It's so nasty and simple... but it just might work!
The user base is on an internal network and of limited size. Bandwidth is not a problem. I'll test performance before I choose this. I can direct the developer teams on where to place the link.
Knowing this and providing it actually works, is there any reason why I shouldn't do this?
My only other option to explore is bundling on the server. I am hoping not to have to resort to this since I don't own the server myself and I am not a .NET developer.
Your proposed approach is an excellent one for your situation. It has several advantages over the more sophisticated solutions, including utter simplicity, completely predictable order of execution, and full compatibility with scripts that may not lend themselves to asynchronous loading. I have used it many times in production applications, as have many other developers.
Of course the other solutions have their advantages too, but for what you're doing there is nothing wrong with good old document.write().
It sounds like you have a number of scripts and stylesheets and are probably loading them from a common directory (or a common root directory). To reduce repetition in your framework.js file, you might want to define two functions, one to write a <link> tag for CSS and another to write a <script> tag for JavaScript. So a skeleton framework.js file might look something like this:
(function() {
var scriptBase = 'js/';
var styleBase = 'css/';
function writeStyle( name ) {
document.write(
'<link rel="stylesheet" href="', styleBase, name, '">',
'</link>'
);
}
function writeScript( name ) {
document.write(
'<script src="', scriptBase, name, '">',
'</script>'
);
}
writeStyle( 'one.css' );
writeStyle( 'two.css' );
writeScript( 'one.js' );
writeScript( 'two.js' );
})();
Note that you don't have to do any special escaping of the </script> text as you may see in code that uses document.write(). That's only necessary when you're putting this code directly inside a <script> tag within the HTML file. The purpose of that escaping is to prevent the enclosing <script> tag from being closed by the </script> text inside the document.write() call. Since your code is in an external .js file this is not an issue: the presence of the </script> text inside this file won't terminate the .js file.
Another point to keep in mind is that all of the document.write() calls you make inside a .js file are inserted into the document after the .js file that writes them. So don't expect to be able to do a document.write() inside framework.js and then have other code inside framework.js that depends on the .js file you just wrote. All of those .js files (and .css) are loaded after framework.js, not interleaved with it.
One more consideration, of course, is load time. Your page could load faster if you combine and minify your CSS and JS files. But if these are internal web apps, page load time may be the least of your worries: reliability and maintainability may be more important. And in any case you can always use the document.write() solution to get up and running right now, and later optimize this only in the unlikely event that you need to.
I want to decrease the time taken by my pages to load and be displayed, assuming I start with an empty browser cache, and the pages may or may not have inline css and javascript in the html file. does changing the order in which files are sent to the browser decrease the display time, and thus make pages seem to be loading faster?
For example if a page has some .css, .js, .png files and so on, would loading the css first, display things faster?
And is there a standard/specific order to load file types?
Here are few steps that could optimize the performance of your web pages.
put css at top.
put javascript at bottom.
cache everything.
set far future expire header.
return 304 when appropriate.
use unique url for css and js for propagating the change.
apart from that use ajax wherever required.
Beware of too many HTTP connections. It takes time to establish an HTTP connection and it can easily eat up loading time if you have many elements linked in your HTML file.
If you have many small icons, glyphs, etc. combine them into a sprite so only one image is loaded. Facebook for instance makes use of the sprite technique - you can see that if you inspect the images it loads.
You can also consolidate your CSS files into one file - same with Javascript files.
Also, if you have JavaScript that affects the content of your page when it loads then make sure to use the event that notifies you when the DOM is ready, instead of waiting for the body loadevent which doesn't trigger until all resources, such as images, CSS files, JavaScript etc is loaded.
js files block page loading until they're executed. When possible, include those before closing body
At first make sure that your webhoster has no slow servers. This can happen on very cheap shared site webhosters. Than you should check that you remove all unnessesary stuff from your html output. Than you could check if your content is dynamic or static. If it is dynamic try to convert it to static content.
In some conditions you can simply activate the caching functions of a CMS that should also help to send the website content faster. Just on slow connections it could be better to use gzip to compress the output stream. But this costs time. The server and also the client have to compress/decompress. You have to check that too.
If you use javascript and the execution is delayed you could also use the ready event to execute your javascript after the html document is loaded (and not all images and so on) like using the document.onload event.
You can save your page load time to use few trick like :- CSS image sprites rather than call every single image for every single purpose this will Minimize your website's HTTP Requests, remove unnecessary div tags or unnecessary code from your HTML-Markup & CSS
Where we can get good results through CSS and so we should not use Jscripts there.
Should make always clean HTML-Markup without any irreverent code.
Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times.
The solutions turned out the simple, combine all the different files into a single large file and compress that file using zip. Unfortunately, if you do this manually you are going to run into maintenance problems. That single compressed file is no longer editable. So after editing one of the original source files you will have to re-combine it with the other files and re-compress it.
Quick question, I have some scripts that only need to be run on some pages and some only on a certain page, would it be best to include the script at the bottom of the actual page with script tags or do something like in my js inlcude;
var pageURL = window.location.href;
if (pageURL == 'http://example.com') {
// run code
}
Which would be better and faster?
The best is to include the script only on pages that need it. Also in terms of maintenance your script is more independant from the pages that are using it. Putting those ifs in your script makes it tightly coupled to the structure of your site and if you decide to rename some page it will no longer work.
I can recommend you to use an asynchrounous resource loader, LAB.js for example. Then you could build a dependencies list, for instance:
var MYAPP = MYAPP || {};
/*
* Bunches of scripts
* to load together
*/
MYAPP.bunches = {
defaults: ["libs/jquery-1.6.2.min.js"],
cart: ["plugins/jquery.tmpl.min.js",
"libs/knockout-1.2.1.min.js",
"scripts/shopping-cart.js"],
signup: ["libs/knockout-1.2.1.min.js",
"scripts/validator.js"]
/*
... etc
*/
};
/*
* Loading default libraries
*/
$LAB.script(MYAPP.defaults);
if (typeof MYAPP.require !== 'undefined') {
$LAB.script(MYAPP.dependencies[MYAPP.require]);
}
and in the end of your page you could write:
<script type="text/javascript">
var MYAPP = MYAPP || {};
MYAPP.require = "cart";
</script>
<script type="text/javascript" src='js/libs/LAB.min.js'></script>
<script type="text/javascript" src='js/dependencies.js'></script>
By the way, a question to everyone, is it a good idea to do so?
In so far as possible only include the scripts on the pages that requirement. That said, if you're delivering content via AJAX that can be hard to do, since the script might already be loaded and reloading could cause problems. Of course you can deliver code in a script block (as opposed to referencing an external js file), in code delivered via AJAX.
In cases where you need to load scripts (say via a master page) for all pages, but that only apply to certain pages, take advantage of the fact that jQuery understands and deals well with selectors that don't match any elements. You can also use live handlers along with very specific selectors to allow scripts loaded at page load time to work with elements added dynamically later.
Note: if you use scripts loaded via content distribution network, you'll find that they are often cached locally in the browser anyway and don't really hurt your page load time. The same is true with scripts on your own site, if they've already been loaded once.
You have two competing things to optimize for, page load time over the network and page initialization time.
You can minimize your page load time over the network by taking maximum advantage of browser caching so that JS files don't have to be loaded over the network. To do this, you want as much javascript code for your site in on or two larger and fully minimized JS files. To do this, you should put JS for multiple different pages in one common JS file. It will vary from site to site whether the JS for all pages should be ine one or two larger JS files or whether you group it into a small number of common JS files that are each targeted at part of your site. But, the general idea is that you want to combine the JS code from different pages into a common JS file that can be most effectively cached.
You can minimize your page initialization time by only calling initialization code that actually needs to execute on the particular page that is being displayed. There are several different ways to approach this. I agree with the other callers that you do not want to be looking at URLs to decide which code to execute because this ties your code to the URL structure which is better to avoid. If your code has a manageable number of different types of pages, then I'd recommend identifying each of those page types with a unique class name on the body tag. You can then have your initialization code look for the appropriate class on the body tag and branch to the appropriate initialization code based on that. I've even seen it done where you find a class name with a particular common prefix, parse out the non-common part of the name and call an initialization function by that name. This allows you to give a page a specific set of behaviors by only adding a classname to the body tag. The code remains very separate from the actual page.
the less general purpose way of doing this is to keep all the code in the one or two common JS files, but to add the appropriate initialization call to each specific page's HTML. So, the JS code that does the initialization code lives in the common JS files and thus is maximally cached, but the calling of the appropriate initialization code for that page is embedded inline in each specific page. This minimizes the execution time of the initialization, but still lets you use maximal caching. It's slightly less generic than the class name technique mentioned earlier, but some may like the more direct calling technique.
Include scripts at bottom of pages that need it only.
The YSlow add-on is the best solution to know why your website is slow.
There are many issues which could be the reason for slowness.
Combining many jQuery to one could help you increasing your performance.
Also you can put the script at the bottom of your page and CSS at top.
Its basically up to you and depends on what the code is.
Generally with small things I will slip it into the bottom of the page. (I'm talking minor ui things that relate only to that page).
If you're doing the location ref testing for more than a couple pages it probably means you're doing something wrong.
You might want to take a look at one of these:
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
http://2tbsp.com/node/91
And as for which is faster it's wildly negligible, pick what is easier for you to maintain.
In todays modern age, where lots of (popular) javascripts files are loaded externally and locally, does the order in which the javascripts files are called matter especially when all local files are all combined (minified) into one file?
Furthermore, many claim that Javascript should go in the bottom of the page while others say javascript is best left in the head. Which should one do when? Thanks!
google cdn latest jquery js | external
another cdn loaded javascript js | external
TabScript ...js \
GalleryLightbox ...js \
JavascriptMenu ...js \
HTMlFormsBeautifier ...js > all minified and combined into one .js file!
TextFieldResize ...js /
SWFObjects ...js /
Tooltips ...js /
CallFunctions ...js /
Order matters in possibly one or more of the following situations:
When one of your scripts contains dependencies on another script.
If the script is in the BODY and not the HEAD.. UPDATE: HEAD vs BODY doesn't seem to make a difference. Order matters. Period.
When you are running code in the global namespace that requires a dependency on another script.
The best way to avoid these problems is to make sure that code in the global namespace is inside of a $(document).ready() wrapper. Code in the global namespace must be loaded in the order such that executed code must first be defined.
Checking the JavaScript error console in Firebug or Chrome Debugger can possibly tell you what is breaking in the script and let you know what needs to be modified for your new setup.
Order generally doesn't matter if functions are invoked based on events, such as pageload, clicks, nodes inserted or removed, etc. But if function calls are made outside of the events in the global namespace, that is when problems will arise. Consider this code:
JS file: mySourceContainingEvilFunctionDef.js
function evilGlobalFunctionCall() {
alert("I will cause problems because the HTML page is trying to call " +
"me before it knows I exist... It doesn't know I exist, sniff :( ");
}
HTML:
<script>
evilGlobalFunctionCall(); // JS Error - syntax error
</script>
<!-- Takes time to load -->
<script type="text/javascript" src="mySourceContainingEvilFunctionDef.js"></script>
...
In any case, the above tips will help prevent these types of issues.
As a side note, you may want to consider that there are certain speed advantages to utilizing the asynchronous nature of the browser to pull down resources. Web browsers can have up to 4 asynchronous connections open at a time, meaning that it's quite possible that your one massive script might take longer to load than that same script split up into chunks! There is also Yahoo Research that shows combining scripts produces the faster result, so results vary from one situation to another.
Since it's a balance between the time taken to open and close several HTTP connections vs the time lost in limiting yourself to a single connection instead of multiple asynchronous connections, you may need to do some testing on your end to verify what works best in your situation. It may be that the time taken to open all of the connections is offset by the fact that the browser can download all the scripts asynchronously and exceed the delays in opening/closing connections.
With that said, in most cases, combining the script will likely result in the fastest speed gains and is considered a best practice.
Yes, depending very much on what you do.
For example, if a.js had...
var a = function() {
alert('a');
}
...and b.js had...
a()
...then you wouldn't want to include b.js before a.js, or a() won't be available.
This only applies to function expressions; declarations are hoisted to the top of their scope.
As for whether you should combine jQuery, I reckon it would be better to use the Google hosted copy - adding it to your combined file will make it larger when there is a great chance the file is already cached for the client.
Read this post from the webkit team for some valuable information about how browsers load and execute script files.
Normally when the parser encounters an
external script, parsing is paused, a
request is issued to download the
script, and parsing is resumed only
after the script has fully downloaded
and executed.
So normally (without those async or defer attributes), scripts get excuted in the order in which they are specified in the source code. But if the script tags are in the <head>, the browser will first wait for all scripts to load before it starts executing anything.
This means that it makes no difference if the script is splitted into multiple files or not.
If I'm understanding your question I think you're asking if it matters where in a file a function/method is defined, and the answer is no, you can define them anywhere in a single source file. The JavaScript parser will read in all symbols before trying to run the code.
If you have two files that define variables or functions with the same name, the order that they're included will change which one actually is defined