javascriptjqueryperformancecufon

Check Element Exists Before Apply Cufon


I have an array of elements #document h1, #content h2 which I know may be present on pages throughout my site; some pages not all.

What I'm doing is iterating through the array and checking if the element exists - if it doesn't I splice it from the array. I then use the toString method to pass the remaining elements to Cufon.

<script>
    $(function(){

        var eurostyle = ["#container h1","#content h2","#content h3","#content h4","#content .sidebar ul span", "#sitenav ul.menu span"];

        for (i=eurostyle.length-1;i >=0;i--) {  
            if (!$(eurostyle[i]).length) {
                eurostyle.splice(i,1);
            }
        }

        Cufon.replace(eurostyle.toString(),{fontFamily: "Eurostile"});

    });
</script>

I'm curious if this technique is worth it?
Does it improve performance or does checking to see if each element exists, actually slow the browser?


Solution

  • Cufon already checks if they exist using jquery's selector engine (assuming it is present). The simpler the selector the less processing power you will use.

    Unfortunately following this path may lead to very krufty markup.

    My thoughts are that your code is just duplicating with cufon does anyway.