/    Sign up×
Community /Pin to ProfileBookmark

Need help streamlining a script

I checked my website with [url=http://www.websiteoptimization.com/services/analyze/]Web Page Analyzer[/url], and my single script (which handles the dual function of pop up menus and tabbed menus) is way too big for its liking. The site says that scripts should be under 8KB, this is over 12.

So here’s a page that showcases the script:

[url]http://mrinitialman.furtopia.org/furcadia.php[/url]

And here’s the script itself:

[url]http://mrinitialman.furtopia.org/webpagefiles/javascript/mainpagescripts.js[/url]

How can I get this under 8K?

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@Declan1991May 31.2008 — I actually did it for you, but here is how. First of all, JSON. So:[code=php]
var a1 = new Array(1,2,3,4,5);
var a2 = [1,2,3,4,5];
var b1 = new Array(new Array(1,2,3),new Array(1,2,3),new Array(1,2,3));
var b2 = [[1,2,3],[1,2,3],[1,2,3]];
[/code]

Shorter variable names (you don't have to be as extreme as I was here all the time, but a variable of 10 or more characters is simply bloat.
[code=php]var subscriptions;
var s;[/code]

Multiple variable declarations on one line:[code=php]
var a = 0, b = 1, c = 2;
var a = 0;
var b = 1;
var c = 2;
[/code]

and minification:[url=http://fmarcia.info/jsmin/test.html]JS Minifier[/url]

I also made a few minor alterations like, running a for loop backwards when the order doesn't matter:[code=php]
for (var i = array.length-1; i >= 0; i--) {

}
[/code]
and storing the array length as a local variable:[code=php]
for (var i = 0, il = array.length; i < il; i++) {

}
[/code]


Minified:[code=php]AddStylesheet('javascript','./WebPageFiles/CSS/MainPageCSS/','MainPageJS');MainPageSetup();if(GetText(GetThisScript())=='Tabs'){StartTabMenuScript();}function MainPageSetup(){var expandable_links=[GetElement('LibraryLink'),GetElement('GalleryLink'),GetElement('BiosLink'),GetElement('LinksLink')];CreateMenus(expandable_links);SetMouseovers(expandable_links);}function CreateMenus(menued_links){var common_attributes=[['class','sub_menu'],['class','sub_menu_link']];var menu_info=[[['Ratings','Story Ratings','ratings'],['Novelettes','Novelettes','novelettes'],['Shorts','Short Stories','shorts'],['Essays','Essays','essays'],['Misc','Miscellaneous','misc']],[['Jack','Jack Krowfight','jack'],['Others','Other Characters','others'],['Mine','My Art','mine']],[['John','John-David','johndavid'],['Jack','Jack Krowfight','jackdaniels']],[['GenFurry','General Furry','furry'],['AdultFurry','Adult Furry','adultfurry'],['UnFurry','Non-Furry','unfurry'],['LinkMe','Link To Me','linkme']]];var menu_ids=['Library','Gallery','Bios','Links'];for(var i=0,il=menu_ids.length;i<il;i++){var menu_list=Create_Element('ul','popmenu',menu_ids[i]+'LinkMenu',common_attributes[0]);var menu_links=[];for(var j=0,jl=menu_info[i].length;j<jl;j++){var anchor_tag=Create_Element('a','popmenu','none',['href','./'+menu_ids[i].toLowerCase()+'.php?section='+menu_info[i][j][2]]);WriteText(anchor_tag,menu_info[i][j][1])menu_link_id=menu_ids[i]+'_'+menu_info[i][j][0];menu_links[j]=Create_Element('li','popmenu',menu_link_id,common_attributes[1]);menu_links[j].appendChild(anchor_tag);menu_list.appendChild(menu_links[j]);}menued_links[i].appendChild(menu_list);}}function SetMouseovers(menued_links){for(var i=0,il=menued_links.length;i<il;i++){menued_links[i].onmouseover=function(i){return function(){SubMenu_Show(menued_links[i].getAttribute('id')+'Menu')}}(i);menued_links[i].onmouseout=function(i){return function(){SubMenu_Hide(menued_links[i].getAttribute('id')+'Menu')}}(i);}}function SubMenu_Show(i){document.getElementById(i).style.display='block';}function SubMenu_Hide(i){document.getElementById(i).style.display='none';}function StartTabMenuScript(){subsection_nav=InsertNavDiv();var m=CreateMenu();var c=CreateCurrent();var t=SetTabInfo();m.subsections=ArrayToTable(GetElement('elal_div','subsection'),t.rowlength);m.rows=SetUpRows(m.subsections,t,subsection_nav);m.tabs=SetUpTabs(m.subsections,m.rows,t);SetSubSecClicks(m,c);FirstShow(c,m);}function InsertNavDiv(){var b=document.body;var n=Create_Element('div','tabmenu','SubSecNav',false);var d=GetElement('Main');var s=GetElement('el_0_h2');d.removeChild(s);b.removeChild(d);b.appendChild(s);b.appendChild(n);b.appendChild(d);subsection_header=Create_Element('div','tabmenu','SubSecHeader',false)WriteText(subsection_header,"Section Navigation");n.appendChild(subsection_header);return n;}function SetTabInfo(){tabinfo=new Object();tabinfo.rowlength=2;tabinfo.width=210;tabinfo.height=20;return tabinfo;}function CreateMenu(){menu=new Object();menu.subsections;menu.tabs;menu.rows;return menu;}function CreateCurrent(){current=new Object();current.subsection='Not Set';current.tab='Not Set';current.row=0;return current;}function SetUpRows(subsection_arr,tabinfo,subsection_nav){var s=Create_Element('ul','tabmenu','SubSecNavMain',false);Styling(s,SetMenuStyling(subsection_arr,tabinfo));var r=[];for(var i=0,il=subsection_arr.length;i<il;i++){r[i]=Create_Element('li','subsection',('SubSecNavRow'+i),'subsection_row');s.appendChild(r[i]);r[i].appendChild(Create_Element('ul','subsection',false,'subsec_tabrow'));}subsection_nav.appendChild(s);return r;}function SetUpTabs(s,r,t){var tm=[];var ti=[];attributes_arr=[['class','subsection_tab'],['row',null],['title',null]];tab_attributes=[['height',(t.height+'px')],['width',(t.width+'px')],['lineHeight',(t.height+'px')],['marginTop',''],['marginLeft','']]for(var i=0,il=s.length;i<il;i++){tm[i]=[];ti[i]=[];attributes_arr[1][1]=i;for(var j=0,jl=s[i].length;j<jl;j++){tab_attributes[3][1]=(j==0)?('0px'):('-'+(t.height+2)+'px');tab_attributes[4][1]=(j*(t.width+1))+'px';attributes_arr[2][1]=GetText(s[i][j].getElementsByTagName('h3')[0]);tm[i][j]=Create_Element('li','subsection',(s[i][j].id),attributes_arr);WriteText(tm[i][j],(subsections[i][j].getElementsByTagName('h3')[0].getAttribute('title')));Styling(tm[i][j],tab_attributes);r[i].firstChild.appendChild(tm[i][j]);if(s[i].length<t.rowlength){SetLastTab(tm[i][j],t.width,t.rowlength,tm[i].length);}}}return tm;}function SetMenuStyling(a,t){var c=0;for(var i=0,il=a.length;i<il;i++){if(a[i].length>c){c=a[i].length;}}return[['width',(((c*(t.width+1))-1)+'px')],['height',((a.length*(t.height+1))-1)+'px']];}function SetSubSecClicks(s,c){for(var i=0,il=s.tabs.length;i<il;i++){for(var j=0,jl=s.tabs[i].length;j<jl;j++){s.tabs[i][j].onclick=function(i){return function(j){return function(){c.subsection=SubSecDisplay(s.subsections[i][j],c.subsection);c.tab=TabHighlight(s.tabs[i][j],c.tab);}}(j)}(i);}}}function SubSecDisplay(s,sh){if(sh!='Not Set'){sh.style.display='none';}s.style.display='block';return s;}function TabHighlight(t,st){if(st!='Not Set'){st.style.backgroundColor='white';st.style.color='black';}t.style.backgroundColor='gray';t.style.color='white';return t;}function FirstShow(c,s){c.subsection=SubSecDisplay(s.subsections[0][0],c.subsection);c.tab=TabHighlight(s.tabs[0][0],c.tab);}function SetLastTab(t,w,l,ll){m=w/(l/ll)+1;t.style.marginLeft=m+'px';}function Create_Element(t,o,i,a){var e=document.createElement(t);e.setAttribute('origin',o+'.js');if(i){e.setAttribute('id',i);}if(a){if(typeof a=='string'){e.className=a;}else if(typeof a[0]=='string'){e.setAttribute(a[0],a[1]);}else{for(var j=a.length-1;j>=0;j--){e.setAttribute(a[j][0],a[j][1]);}}}return e;}function WriteText(e,t){e.appendChild(document.createTextNode(t));}function GetText(t_){do{var c=true;t_=t_.firstChild;if(t_==undefined){c=false;}if(c){if(t_.nodeType==3){c=false;}}}while(c);return(t_==undefined)?"No_Text_Error":t_.data;}function Styling(e,s){if(typeof e=='string'){e=GetElement(e);}if(typeof s[0]=='string'){e.style[s[0]]=s[1];}else{for(var i=0,il=s.length-1;i<il;i++){e.style[s[i][0]]=s[i][1];}}}function AddStylesheet(s,r,id){var u=r+s+'.css';var a=[['rel','stylesheet'],['type','text/css'],['href',u]]var ss=Create_Element('link',s,id,a);GetElement('el_0_head').appendChild(ss);}function GetElement(i_,f){var e,t_=i_.substr(0,5),n_=i_.substr(5);if(t_=='elal_'){var el=document.getElementsByTagName(n_);if(f){e=FilterElement(el,f);}else{e=el;}}else if(type_.substr(0,3)=='el_'){var w=t_.substr(3,1);e=document.getElementsByTagName(n_)[w];}else{e=document.getElementById(i_);}return e;}function FilterElement(el,f){var s=0,e=[],i=0,is=el.length;if(typeof f=='string'){while(i<is){if(el[i].className.match(f)){e[s]=el[i];s++;}i++;}}else{while(i<is){if(el[i].getAttribute(f[0])==f[1]){e[s]=el[i];s++;}i++;}}if(e.length==0){var a;var v_;if(typeof f=='string'){a='class';v_=f;}else{a=f[0];v_=f[1];}alert("Filter Error: All elements discarded. Check filter settings in function call.nFilter is: "+a+" = "+v_);}return e;}function GetThisScript(){sc=document.getElementsByTagName('script');return sc[sc.length-1];}function ArrayToTable(a,pl){var na=[],i=0;while((a.length>pl)){na[i]=a.splice(0,pl);i++;};na[i]=a;return na;}[/code](7266 bytes)

There may be a few small glitches now, if I missed a variable here and there, but if there is, use the non-minified code, and fix the problem, and then minify it. You can see how much difference using short variable names can make. You can also gzip it and you could probably get it down to four kilobytes.
Copy linkTweet thisAlerts:
@Declan1991May 31.2008 — Code that isn't minified:[code=php]AddStylesheet('javascript', './WebPageFiles/CSS/MainPageCSS/', 'MainPageJS');
MainPageSetup();
if(GetText(GetThisScript()) == 'Tabs'){
StartTabMenuScript();
}

// Popup Menus
function MainPageSetup(){
var expandable_links = [
GetElement('LibraryLink'),
GetElement('GalleryLink'),
GetElement('BiosLink'),
GetElement('LinksLink')
];
CreateMenus(expandable_links);
SetMouseovers(expandable_links);
}
function CreateMenus(menued_links){
var common_attributes = [
['class', 'sub_menu'],
['class', 'sub_menu_link']
];
var menu_info = [
[
['Ratings', 'Story Ratings', 'ratings'],
['Novelettes', 'Novelettes', 'novelettes'],
['Shorts', 'Short Stories', 'shorts'],
['Essays', 'Essays', 'essays'],
['Misc', 'Miscellaneous', 'misc']
],
[
['Jack', 'Jack Krowfight', 'jack'],
['Others', 'Other Characters', 'others'],
['Mine', 'My Art', 'mine']
],
[
['John', 'John-David', 'johndavid'],
['Jack', 'Jack Krowfight', 'jackdaniels']
],
[
['GenFurry', 'General Furry', 'furry'],
['AdultFurry', 'Adult Furry', 'adultfurry'],
['UnFurry', 'Non-Furry', 'unfurry'],
['LinkMe', 'Link To Me', 'linkme']
]
];
var menu_ids = ['Library', 'Gallery', 'Bios', 'Links'];
for(var i = 0, il = menu_ids.length; i < il; i++){
var menu_list = Create_Element('ul', 'popmenu', menu_ids[i] + 'LinkMenu', common_attributes[0]);
var menu_links = [];
for(var j = 0, jl = menu_info[i].length; j < jl; j++){
var anchor_tag = Create_Element(
'a',
'popmenu',
'none',
['href', './' + menu_ids[i].toLowerCase() + '.php?section=' + menu_info[i][j][2]]
);
WriteText(anchor_tag, menu_info[i][j][1])
menu_link_id = menu_ids[i] + '_' + menu_info[i][j][0];
menu_links[j] = Create_Element('li', 'popmenu', menu_link_id, common_attributes[1]);
menu_links[j].appendChild(anchor_tag);
menu_list.appendChild(menu_links[j]);
}
menued_links[i].appendChild(menu_list);
}
}

function SetMouseovers(menued_links){
for(var i = 0, il = menued_links.length; i < il; i++){
menued_links[i].onmouseover = function(i){return function(){SubMenu_Show(menued_links[i].getAttribute('id') + 'Menu')}}(i);
menued_links[i].onmouseout = function(i){return function(){SubMenu_Hide(menued_links[i].getAttribute('id') + 'Menu')}}(i);
}
}

function SubMenu_Show(i){
document.getElementById(i).style.display = 'block';
}
function SubMenu_Hide(i){
document.getElementById(i).style.display = 'none';
}

// Tabbed Menus

function StartTabMenuScript(){
subsection_nav = InsertNavDiv();
var m = CreateMenu();
var c = CreateCurrent();
var t = SetTabInfo();
m.subsections = ArrayToTable(GetElement('elal_div', 'subsection'), t.rowlength);
m.rows = SetUpRows(m.subsections, t, subsection_nav);
m.tabs = SetUpTabs(m.subsections, m.rows, t);
SetSubSecClicks(m, c);
FirstShow(c, m);
}
function InsertNavDiv(){
var b = document.body;
var n = Create_Element('div', 'tabmenu', 'SubSecNav', false);
var d = GetElement('Main');
var s = GetElement('el_0_h2');
d.removeChild(s);
b.removeChild(d);

b.appendChild(s);
b.appendChild(n);
b.appendChild(d);
subsection_header = Create_Element('div', 'tabmenu', 'SubSecHeader', false)
WriteText(subsection_header, "Section Navigation");
n.appendChild(subsection_header);
return n;
}
function SetTabInfo(){
tabinfo = new Object();
tabinfo.rowlength = 2;
tabinfo.width = 210;
tabinfo.height = 20;
return tabinfo;
}
function CreateMenu(){
menu = new Object();
menu.subsections;
menu.tabs;
menu.rows;
return menu;
}
function CreateCurrent(){
current = new Object();
current.subsection = 'Not Set';
current.tab = 'Not Set';
current.row = 0;
return current;
}
function SetUpRows(subsection_arr, tabinfo, subsection_nav){
var s = Create_Element('ul', 'tabmenu', 'SubSecNavMain',false);
Styling(s, SetMenuStyling(subsection_arr, tabinfo));
var r = [];
for(var i = 0, il = subsection_arr.length; i < il; i++){
r[i] = Create_Element('li', 'subsection', ('SubSecNavRow' + i), 'subsection_row');
s.appendChild(r[i]);
r[i].appendChild(Create_Element('ul', 'subsection', false, 'subsec_tabrow'));
}
subsection_nav.appendChild(s);
return r;
}
function SetUpTabs(s, r, t){
var tm = [];
var ti = [];
attributes_arr = [
['class', 'subsection_tab'],
['row', null],
['title', null]
];
tab_attributes = [
['height', (t.height + 'px')],
['width', (t.width + 'px')],
['lineHeight', (t.height + 'px')],
['marginTop', ''],
['marginLeft', '']
]
for(var i = 0, il = s.length; i < il; i++){
tm[i] = [];
ti[i] = [];
attributes_arr[1][1] = i;
for(var j = 0, jl = s[i].length; j < jl; j++){
tab_attributes[3][1] = (j==0)?('0px'):('-' + (t.height + 2) + 'px');
tab_attributes[4][1] = (j * (t.width + 1)) + 'px';
attributes_arr[2][1] = GetText(s[i][j].getElementsByTagName('h3')[0]);
tm[i][j] = Create_Element('li', 'subsection', (s[i][j].id), attributes_arr);
WriteText(
tm[i][j],
(subsections[i][j].getElementsByTagName('h3')[0].getAttribute('title'))
);
Styling(tm[i][j], tab_attributes);
r[i].firstChild.appendChild(tm[i][j]);
if(s[i].length < t.rowlength){
SetLastTab(tm[i][j], t.width, t.rowlength, tm[i].length);
}
}
}
return tm;
}
function SetMenuStyling(a, t){
var c = 0;
for(var i=0, il = a.length; i < il; i++){
if(a[i].length > c){
c = a[i].length;
}
}
return [
['width', (((c * (t.width + 1)) - 1) + 'px')],
['height', ((a.length * (t.height + 1)) - 1) + 'px']
];
}
function SetSubSecClicks(s, c){
for(var i = 0, il = s.tabs.length; i < il; i++){
for(var j = 0, jl = s.tabs[i].length; j < jl; j++){
s.tabs[i][j].onclick = function(i){
return function(j){
return function(){
c.subsection = SubSecDisplay(s.subsections[i][j], c.subsection);
c.tab = TabHighlight(s.tabs[i][j], c.tab);
}
}(j)
}(i);
}
}
}
function SubSecDisplay(s, sh){
if(sh!='Not Set'){
sh.style.display = 'none';
}
s.style.display = 'block';
return s;
}
function TabHighlight(t, st){
if(st!='Not Set'){
st.style.backgroundColor = 'white';
st.style.color = 'black';
}
t.style.backgroundColor = 'gray';
t.style.color = 'white';
return t;
}
function FirstShow(c, s){
c.subsection = SubSecDisplay(s.subsections[0][0], c.subsection);
c.tab = TabHighlight(s.tabs[0][0], c.tab);
}
function SetLastTab(t, w, l, ll){
m = w / (l / ll) + 1;
t.style.marginLeft = m + 'px';
}

// General Functions


// Element Creation function
function Create_Element(t, o, i, a){
var e = document.createElement(t);
e.setAttribute('origin', o + '.js');
if(i){
e.setAttribute('id', i);
}
if(a){
if(typeof a == 'string'){
e.className = a;
} else if(typeof a[0] == 'string'){
e.setAttribute(a[0], a[1]);
} else {
for(var j = a.length-1; j >= 0; j--){
e.setAttribute(a[j][0], a[j][1]);
}
}
}
return e;
}


// Text Functions
function WriteText(e, t){
e.appendChild(document.createTextNode(t));
}

function GetText(t_){
do {
var c = true;
t_ = t_.firstChild;
if(t_ == undefined){
c = false;
}
if(c){
if(t_.nodeType == 3){
c = false;
}
}
} while(c);
return (t_ == undefined)?"No_Text_Error":t_.data;
}

// Inline Style Functions

function Styling(e, s){
if(typeof e == 'string'){
e = GetElement(e);
}
if (typeof s[0] == 'string'){
e.style[s[0]] = s[1];
} else {
for(var i = 0, il = s.length-1; i<il; i++){
e.style[s[i][0]] = s[i][1];
}
}
}

// Stylesheet Functions

function AddStylesheet(s, r, id){
var u = r + s + '.css';
var a = [
['rel', 'stylesheet'],
['type','text/css'],
['href',u]
]
var ss = Create_Element(
'link',
s,
id,
a
);
GetElement('el_0_head').appendChild(ss);
}

// Get an Element

function GetElement(i_, f){
var e, t_ = i_.substr(0,5), n_ = i_.substr(5);
if(t_=='elal_'){
var el = document.getElementsByTagName(n_);
if(f){
e= FilterElement(el, f);
} else {
e = el;
}
} else if(type_.substr(0,3)=='el_'){
var w = t_.substr(3,1);
e = document.getElementsByTagName(n_)[w];
} else {
e = document.getElementById(i_);
}
return e;
}

// Filter elements by attribute. Default attribute is "class"

function FilterElement(el, f){
var s = 0, e = [], i = 0, is = el.length;
if(typeof f=='string'){
while(i < is){
if(el[i].className.match(f)){
e[s] = el[i];
s++;
}
i++;
}
} else {
while(i < is){
if(el[i].getAttribute(f[0])==f[1]){
e[s] = el[i];
s++;
}
i++;
}
}
if(e.length==0){
var a;
var v_;
if(typeof f=='string'){
a='class';
v_ = f;
} else {
a=f[0];
v_ = f[1];
}
alert("Filter Error: All elements discarded. Check filter settings in function call.nFilter is: " + a + " = " + v_);
}
return e;
}

// Get the referring Script element

function GetThisScript(){
sc = document.getElementsByTagName('script');
return sc[sc.length - 1];
}

// Array functions

function ArrayToTable(a, pl){
var na = [], i = 0;
while((a.length > pl)){
na[i] = a.splice(0,pl);
i++;
};
na[i] = a;
return na;
}[/code]
(9394 bytes).
Copy linkTweet thisAlerts:
@Mr_Initial_ManauthorJun 01.2008 — Three questions:

1) What does JSON stand for?

2) How does gzipping work?

3) Can specializing a code to make it more specific to a set of pages cut down on its size?
Copy linkTweet thisAlerts:
@Declan1991Jun 01.2008 — 1) JSON stands for JavaScript Object Notation, and is quite simple. Basically it's [] for arrays and {} for objects.[url=http://json.org/]JSON[/url].

2) Gzipping is a way in which the files are compressed and then sent to the browser to be decompressed. Just look that one up.

3) In a manner of speaking. Generally using small variable names (especially for local variables and parameters) will shed a good bit of weight, but it's pointless having 5kb of stuff you never use. Equally there is no point in making 3 http requests for 1kb each, you are probably better off to make a single one for 6kb. There is no definite answer, except, if you have a set of core functions that you always use, and then a gallery script and a tabbed script. You probably should put that in three files, especially if you are not using the gallery and the tabbed script on the one page. Another option is to have a number of different JavaScript files for every new thing you need. It all depends.

[url=http://developer.yahoo.com/yslow/]YSlow[/url] ([url=http://developer.yahoo.com/performance/rules.html]based on this[/url]) gives very good advice. I follow it mostly and find it very good.
×

Success!

Help @Mr_Initial_Man spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...