The following script works well to both truncate a link and add an icon class BUT,
It was too slow: using document.ready to hold the code from executing UNTIL all the elements on a page loaded.
I removed it, AND it works BUT it won’t work on the last element
<script>
jQuery.noConflict();
jQuery(".resultAction").each(function(){
var fileName = jQuery(this).find('a').html()
var fileExtension = fileName.substring(fileName.lastIndexOf('.') );
var nameChars= fileName.length;
var shorter=fileName.substring(0,10)+"...";
//apply style to relative to file extension
if(fileExtension=="jpg"||"pdf"||"mov"){
jQuery(this).find("#indicator").addClass("is" + fileExtension.slice(1) );
}
//no file extension hide the icon div "indicator"
if((fileExtension.indexOf('.') == -1)){
jQuery(this).find("#indicator").addClass("not");
}
//truncate text
if(nameChars>10){
jQuery(this).find('a').text(shorter);
}
});
</script>
so I got rid of the .ready above and added this over again:
<script>
jQuery(document).ready(function(){
jQuery.noConflict();
jQuery(".resultAction:last").each(function(){
//-SAME CODE ABOVE-....
</script>
-notice the :last -which of course works -but it’s redundant and I was wondering if there is a more efficient way to both make this code run instantly (as the page loads each element) and completely instead of running two identical scripts one to run fast, and one to apply to the last item it missed.
Common code can be put in a function and called from both places you use it, thus only having one copy of the code, but called from multiple places.
and
As for speeding up
jQuery(".resultAction:last"), there are some options:<body>. This will execute a little sooner than domReady and be just as safe.jQuery(".resultAction")just once and save that result. You can then use the whole list or the last one at any time without any further DOM lookups.document.getElementById("item")is more than 10x faster thanjQuery("#item").Also, something is probably wrong with this code:
There should only be one
#indicatorid in your entire document so you should not need to confine it to thethiscontext. So, either you can just use$("#indicator")to get the one object like that or you need to be using a class instead of an id because there are multiple objects like this in the page.