Text width (v2)

Revision 2 of this benchmark created by Igor on


Preparation HTML

<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
<style type='text/css'>
p {
    font-size: 18px;
}
</style>

Setup

$.fn.measureWidth = function () {
      var span = document.createElement('span');
      span.style.whiteSpace = 'nowrap';
      span.style.display = 'inline-block';
      span.style.margin = span.style.padding = 0;
      span.innerHTML = this[0].outerHTML;
      document.body.appendChild(span);
      var width = span.offsetWidth;
      document.body.removeChild(span);
      return width;
  }
  
  $.fn.canvasMeasureWidth = function (font) {
      if (!jQuery._cachedCanvas) {
          var canvas = document.createElement('canvas');
          jQuery._cachedCanvas = canvas.getContext('2d');
      }
      jQuery._cachedCanvas.font = font;
      return jQuery._cachedCanvas.measureText(this[0].innerText).width;
  }
  
  $.fn.canvasMeasureWidthInternal = function () {
      if (!jQuery._cachedCanvas) {
          var canvas = document.createElement('canvas');
          jQuery._cachedCanvas = canvas.getContext('2d');
      }
      var style = this[0].style;
      jQuery._cachedCanvas.font = (style.fontStyle || style.fontVariant || style.fontWeight) + ' ' + style.fontSize + (style.lineHeight ? '/' + style.lineHeight : '') + ' ' + style.fontFamily;
      return jQuery._cachedCanvas.measureText(this[0].innerText).width;
  }
  
  var text = "YOU SHALL NOT PASS!";

Test runner

Ready to run.

Testing in
TestOps/sec
DOM query
$('<p>' + text + '</p>').measureWidth();
ready
Cached canvas
$('<p>' + text + '</p>').canvasMeasureWidth('18px Times New Roman');
ready
Canvas with inline font applied
$('<p style="font: 18px Times New Roman">' + text + '</p>').canvasMeasureWidthInternal();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.