Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

JavaScript Forum


You are currently viewing our JavaScript Forum as a guest. Please register to participate.
Login



Reply
Javascript Compression
Old 04-24-2006, 07:04 PM Javascript Compression
Christopher's Avatar
Iced Cap

Latest Blog Post:
Cross-domain AJAX with JSONP
Posts: 3,110
Location: Toronto, Ontario
Trades: 0
With Javascript becoming a large part of todays websites, the file sizes are beginning to get a bit scary. While it is true most clients will cache Javascript files, a user's first visit means downloading all of that code.

For example, using the Prototype framework costs you about 55KB by default* (as of version 1.5.0rc0). If you want to use other libraries, then you're adding even more. The popular script.aculo.us library, whcih lets you add stunning effects and controls to your pages, adds about 120KB by default**.

So it really is a good idea to compress the Javascript files you upload to your server. No one needs to read them or edit them, so you don't really loose anything.

Just two FYI's on the linked:

* The Prototype framework contains a lot of code you might not need. Try removing classes that you don't need. For example, if you don't use the AJAX class, then remove it.

** By default, when you include the main script.aculo.us script file into your page, it automatically loads the entire library for you. This might be good if you use everything the library has to offer, but if you only use one aspect, then it is a waste. For example, if you only use the effects then you don't want to include 80KB of extra JS you won't use. To remedy this problem, you can edit the main scriptaculous.js source file and modify the load() method to only load the files you need. Or simply include only the files you need and forget about the auto-loading.



Compressors
There are a number of JS compressors available. Many of them rely on complex regular expressions and tricks to squash everything. Sometimes they work, but often times they leave errors in their wake.

The one I like to use is the Dojo Compressor. It does a more simplistic compression compared to some other compressors you might find on the market, but this one works and is totally free. Built on the Rhino Javascript engine from Mozilla, you can be sure your scripts will remain functional even after compression. You can download the JAR and run it locally on your machine, or you can use their online ShrinkSafe application.



I created a batch file for use on my Windows machine that would compress all JS files in a directory and move the real source files into a new directory called '_src'. It's basic, but it works. If you want to write a better version, or want to write a bash script, reply and let the world benefit

Code:
@echo off

rename *.js *.real

for %%I in (*.real) do java -jar custom_rhino.jar -c %%I > %%~nI.js 2>&1

mkdir _src
move *.real _src
cd _src
rename *.real *.js
cd ..
__________________

Please login or register to view this content. Registration is FREE
- Latest Articles:
Please login or register to view this content. Registration is FREE
,
Please login or register to view this content. Registration is FREE

--
Please login or register to view this content. Registration is FREE

Christopher is offline
Reply With Quote
View Public Profile
 
 
Register now for full access!
Old 04-24-2006, 08:39 PM Re: Javascript Compression
Anacrusis's Avatar
Defies a Status

Posts: 2,099
Name: Adam
Location: Colchester CT
Trades: 0
Excellant post Chroder, thanks! I will definatly make use of these tools.
Anacrusis is offline
Reply With Quote
View Public Profile
 
Old 04-25-2006, 01:32 AM Re: Javascript Compression
vangogh's Avatar
Post Impressionist

Posts: 10,688
Name: Steven Bradley
Location: Boulder, Colorado
Trades: 0
Thanks Chroder. I've been looking recently into adding a AJAX to my toolkit and have been wondering how to get all those JavaScript files down to a reasonable size.
__________________
l Search Engine Friendly Web Design |
Please login or register to view this content. Registration is FREE

l Tips On Marketing, SEO, Design, and Development |
Please login or register to view this content. Registration is FREE

l
Please login or register to view this content. Registration is FREE
|
Please login or register to view this content. Registration is FREE
vangogh is offline
Reply With Quote
View Public Profile Visit vangogh's homepage!
 
Old 04-25-2006, 04:19 AM Re: Javascript Compression
ChancesAre's Avatar
Skilled Talker

Posts: 84
Trades: 0
Chroder, thanks very mych for this, this is very helpful
ChancesAre is offline
Reply With Quote
View Public Profile
 
Old 04-26-2006, 12:35 PM Re: Javascript Compression
ibbo's Avatar
Super Spam Talker

Posts: 880
Location: Leeds UK
Trades: 0
Quote:
Originally Posted by vangogh
Thanks Chroder. I've been looking recently into adding a AJAX to my toolkit and have been wondering how to get all those JavaScript files down to a reasonable size.
I use the same file.

I have a daemon.php class that handles all ajax requests and 1 ajax js file that determines what to call by simply calling daemon but with say param=1 as a parameter.

This then makes it all re-usable

PHP Code:
class daemon{

    public 
$getvars = Array();
    public 
$link null;
    
    
    const 
DBHOST   '';
    const 
DBUSER   '';
    const 
DBPASSWD '';
    const 
DBASE    '';
    
    
    const 
GETPOLL   "select id, question from poll_question";
    const 
GETUSERS  "select * from user_details ";
    
    public function 
__construct(){
        
$this->cleanInput();
        
$this->sortDB();
        
$this->process();
        
$this->close();
    }

    public function 
cleanInput(){
        if (!empty (
$_GET)) {
           foreach (
$_GET as $field => $val) {
            
$this->getvars[$field] = trim($val);
          }
        }
    }
    
    public function 
process(){
        
        if(isset(
$this->getvars['poll'])){
            
$result mysql_query(daemon::GETPOLL);
            if(
mysql_num_rows($result) > 0){
              while (
$row mysql_fetch_assoc($result)) {
                  echo 
"<tr>";
                  echo 
"<td>{$row['question']}</td>";
                  echo 
"<td><a href='/results/?id={$row['id']}'>More</a></td>";
                  echo 
"</tr>\n";
              }
            }
        
    }
    
    public function 
sortDB(){
        
$this->link mysql_pconnect(daemon::DBHOSTdaemon::DBUSERdaemon::DBPASSWD
        or die(
'Could not connect: ' mysql_error());
        
mysql_select_db(daemon::DBASE) or die('Could not select database');
        
    }
    
    public function 
close(){
        
mysql_close($this->link);
    }
    
}

new 
daemon(); 
The dog work is done in the process method in here you can catch $_GET['var'] and then perform your action upon it. I.E above I am listing all the polls for our CMS section so they can be stacked up and worked upon.

And my ajax code

Code:
function construct() {

	getRequest(url);
	var node = new Array();
}

function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}  else{ alert('Nos object'); }
}

function getRequest(val) {

	switch(val){
		case 'poll':
		url = 'http://llocaldev.mysite/admin/daemon/daemon.php?poll=1';
		break;
		default:
		url = '';
	}
	
	if(!(params == '' || params == ' ')){
		if (httpReq.readyState == 4 || httpReq.readyState == 0) {
			httpReq.open("GET",url , true);
			httpReq.onreadystatechange = handleText;
			httpReq.send("");
		}
	}
}

function handleText(){
		
	var display_div = document.getElementById("display");
	var pending_div = document.getElementById("pending");

	if (httpReq.readyState == 4) {
	
		if (httpReq.status == 200) {
			pending_div.innerHTML = "";
			display_div.innerHTML = "<table align='center'>" + httpReq.responseText + "</table><br />";
			//display_div.innerHTML = "result";
			//document.write(httpReq.responseText);
		}
	}else{
		pending_div.innerHTML = '<div align="center"><img src="/media/bar.gif" alt="Progress" style="border:1px outset silver;"></div>';
	}
}
In my html page I call getRequest('poll'), the js script switches the val and see's whats what. from here you can append a tag so that the daemon knows what to process. In this case its polls but you can get a fair few hits going on all using the 1 php class and the single ajax script above.

I dont use XML to wrap up my data as I can add links to it etc from my daemon. I do intend to look into Json to make XML style of data transfer plausable but I find wrapping up data in XML can be a nightmare once your set gets to a few hundred rows.

Still code re-use is the motto and re-use it you should. After all they say the best programmers are the lazy ones.

Ibbo
__________________

Please login or register to view this content. Registration is FREE

Please login or register to view this content. Registration is FREE

Please login or register to view this content. Registration is FREE

Please login or register to view this content. Registration is FREE

Linux user #349545 :
(GNU/Linux)iD8DBQBAzWjX+MZAIjBWXGURAmflAKCntuBbuKCWenpm XoA7LNydllVQOwCf

Last edited by ibbo; 04-26-2006 at 12:40 PM..
ibbo is offline
Reply With Quote
View Public Profile Visit ibbo's homepage!
 
Reply     « Reply to Javascript Compression
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.79103 seconds with 12 queries