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
Related
I have 3 questions, but I think the first 2 are very simple, so I'll ask them all here.
I normally work in C++ with SQL (and sometimes with VBA), and I'm trying to figure out the basics of JS, PHP & HTML (I've mostly got the jist of HTML and CSS).
I have 5 different reference books plus the net, but one thing I can't seem to find anything about are the file exts (.js, .php, .html).
From my tests I have come to realize that you can usually run JS scripts in other file types, but PHP seems to require the .php ext.
So the questions are:
Do I always have to use *.php for PHP scripting?
In a SINGLE file, can I delay PHP execution by simply putting the code into a function?
eg
<?php
function test() {echo "hello world";}
//as opposed to:
echo "hello world";
?>
When using multiple files, are there any compelling reasons to (or not to) always put scripts in their corresponding file types (e.g. JS in *.js). Obviously this would make it easier to understand / read, especially as it grows BUT can this create problems?
No, you can use any extension you want. Even if you want, don't use extension at all. But then, tell your server what interpreter to use when he founds he has to parse a *.wtf file. I mean, you're running a the script "file.wtf" from the command line you can do it like this:
$>php file.wtf
but if the script is to be parsed by your favorite web server (like Apache) because it is part of (say) a web page, then you have to configure it to interpret .wtf files with the PHP library.
By simply putting it in a function:no. But you really want to delay execution, use the sleep function
Just what you said: You can mix html and javascript code in your php files, but that is very messy.
I am currently working on the translation of a website.
To perform this translation easily, I created a .csv file containing the matches between the two languages (japanese->english).
Then, this file is parsed with PHP, and ob_start() is called on the page in order to replace wanted strings.
Here is the script :
function lang_modify($buffer){
require('get_messages.php');
for($i=0; $i<count($messages); $i++){
$buffer = str_replace($messages[$i][0], $messages[$i][1], $buffer);
}
return $buffer;
}
$buffer = ob_start('lang_modify');
This script works perfectly on php/html files. However, ob_start does not read javascript files so I was wondering if someone knows a way to include javascript files into the output buffer so that the ob_start() function will replace the words found in javascript as well.
Someone adviced me to do search something with the AddFile statement (.htaccess), but I don't know at all how could I use this to do what I want.
Does anyone have a clue ?
What you are facing here, is a Separation of Concerns issue.
Your translation is generated from PHP.
And yet, your javascript displays and (sometimes) generates those messages.
How do i fix this?
1) Make sure your translations comes from one single source, ideally from PHP
2) Use an i18n js library to process your translations. I suggest: https://airbnb.github.io/polyglot.js/
3) If you are using Polyglot, make sure that your PHP translations are being generated into a js file, which is then loaded based on localisation.
Polygot will translate your default messages into internationalized ones.
In short:
Enable Modularity - Administer(CRUD) all your translations in PHP. Storing them in a database
would be ideal
Decouple JS from translation - Polygot will only provide the translated messages to your views(HTML).
I am making a browser game (client side only). I am trying to make it smaller (meaning file sizes), which is first step for mobile version. I have minified CSS using LESS, JS using uglify and also angular templates using grunt-angular-templates. So at this moment I am loading very small number of files:
index.html
app.js
app.css
images.png (one file with all images)
But the remaining problem are JSON data files. There are (or will be) many levels and each level has its own JSON data file. Also there are some rule definitions etc. The problem is, that these JSON files are loaded dynamically when needed.
I am now trying to find a way, how to somehow get these files (at build time, probably some grunt task) into one file, or even better - directly into app.js. I have no problem in writing PHP script + JS class, that would do this, but I first tried to find some finished solution.
Does anybody know about something like that, or is there any other solution that I am not thinking about? Thanks for any help.
====
EDIT:
1) The point of this is getting rid of X requests and making one request (or zero) for JSON files.
2) The compiled thing does not have to be JSON at all. Part of my idea:
JsonManager.add('path/to/json/file.json', '{"json":"content of file"}');
making all these lines manually is bad idea, I was asking about something, if there is anything, that could do this job for me.
3) Ideally i am looking for some solution similar to what grunt-angular-templates task does with HTML templates (minifies them and adds them to app.js using Angular's $templateCache)
Say you have two JSONs: {'a':1} and {'b':2}.
You cannot simply concatenate them into one chunk as together they will not be a valid JSON, e.g. this {'a':1}{'b':2} is not valid JSON. You can do this with JS and CSS but not JSON.
The only option is to include them into larger structure:
[
{'a':1},
{'b':2}
]
If your code structure allows to do this then you can use any existing JS compressor/uglifier to compress the result.
For anybody who has same problem as me:
I gave up finding already finished solution, and made my own:
The solution
I have written PHP script, that iterates over files in data directory and lists all JSON files. It also minifies their contents and creates one big array, with keys as relative file names and values as JSON content of files. It then creates a .js file, in which this big array is encoded as JSON again and given to a JavaScript variable (module constant in my case - Angular)
I created a wrapper class, which serves this data as files, e.g.:
var data = dataStorage.getData('levels/level01.json'); // returns JSON content of file located at path/to/data/files/levels/level01.json but without any AJAX call or something
I used grunt-shell to automate running this php file
I added the result .js file to list of files, which should be minified by uglify (and connected together).
The result:
I can create any number of JSON files in any structure and link to them from js code using that wrapper class, but no AJAX calls are fired.
I decreased number of files needed to load at startup (but increased app.js size a bit, which is better than second request).
Thanks for your ideas and help. Hope this also helps someone
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/
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.