I need to be able to find the width of a string variable if it were to be displayed on the screen. The technique I've found for doing this entails using a span, filling it with the string in question and then measuring the width of that span. Unfortunately I need to calculate the width of my string a couple hundred times during the loading of my page to determine the dimensions of various elements on my screen. The calls to the existing version of this function takes about 95% of my execution time and I'm wondering if there's a faster way to calculate the width of a string that maybe doesn't use the DOM which I'm assuming is why this function is bottlenecking my page. The code I'm using to calculate string width presently looks like this:
<script>
String.prototype.strWidth = function(){
$("#ruler").html(this);
return $("#ruler").width();
};
</script>
<span id="ruler" style="visibility:hidden;white-space:nowrap"></span>