[jQuery] Assistance with code efficiency and speed
Hello everyone,
I'm new to jQuery and have learned a lot from this list. I'm posting
a code segment below that reads an HTML table and appends a link to a
form if a table cell contains the word 'Offsite'.
On some pages this will require appending up to 300 links, so load
time has become an issue. I picked up the setTimeout trick from this
list and it's working well but I would like to add performance and
trim code as much as possible. Are there any obvious things I'm doing
inefficiently below? I'm not sure what is the best way to place the
sub-functions so they are all within document.ready.
As I said, the code is working fine as is, I'm just hoping to speed it
up if possible. Thanks.
(function($) {
$('document').ready(function() {
//constants for html
var left_link_html = "<a class='request_form_link' href=\"/screens/
recap_form.html?bcode="
var right_link_html = "\" onclick=\"window.open(this.href, '_blank',
'toolbar=no,location=no,directories=no,resizable=yes,scrollbars=no,menubar=yes,width=550,height=500');
return false;\">Request</a>"
var barcode_pattern = /(35005){1}[0-9]{8}.*/;
var offsite_rows = $("tbody tr.bibItemsEntry:contains(Offsite)
td:contains(35005)")
//function to trim leading white space
function trim_barcode(code){
var re = /^\s/;
var code = code.replace(re, "")
return code;
}
//function to create form html
function form_html(code_spot, barcode, title){
if (barcode.match(barcode_pattern)) {
var form_html = $(code_spot).append([
left_link_html,
barcode,
"?title=",
title,
right_link_html
].join(""));
var add_row_highlight = $
('table.bibItems').addClass('highlight_row');
}
return;
}
//grabs the title if it appears on the page
function title_find (){
var title = $("td.bibInfoData strong")[0]
if (!title) var title=""
else{
$(title).addClass('bib-title')
var title = $(title).text()
var title = escape(title)
}
return title;
}
//recap section
//grab date and time for setTimeout function
var start=new Date().getTime();
var title = title_find();
offsite_rows.each(function (){
var code_spot = $(this)[0];
var barcode = trim_barcode($(code_spot).text());
//slow down if loading takes longer than 2 seconds. setTimeout
requires function wrapper
if(new Date().getTime()-start>2000){
var form_w_code = setTimeout(function(){form_html(code_spot,
barcode, title)},0)
}//ends if
else{
var form_w_code = form_html(code_spot, barcode, title)
}//ends else
}); //ends function
});
})(jQuery);