text-overflow: ellipsis - Extremely fast implementation in JavaScript

There was many approaches of how to nicely fit certain amount of text inside fixed-size HTML blocks. For example when it comes to show a list of short descriptions often your layout want to have exactly 300px width and maximum 3 lines of text per description. I made one more JavaScript solution for that problem.

Why I did it?

I used to simply use overflow:hidden just to hide too big text, but in the last project there was need to have nice ellipsis (...) at the end of every "short description".

First I found CSS property text-overflow: ellipsis which is essentially the thing what I was looking for. But there is serious problem - it works only for one-line text only and it doesn't work for every browser.

So I moved further and found jQuery.ThreeDots plugin which works quite good but it is very slow as it is operating on DOM model and it is noticeable for user that somethings happen on his screen - first shows whole text and right away this text gets ellipsised.

Lastly - my project is dedicated to Samsung Smart TV - where overall performance is very bad so direct operations on DOM like above's jQuery.ThreeDots just kills the machine. 

I sit down, spent few hours and created new project which implements ellipsis functionality in JavaScript. It is extremely fast and reproduce ellipsis functionality quite good.

The FastEllipsis 

Key features:
  • As little as possible use of DOM to determine widths of basic ASCII characters
  • Create cache for all chars and words used so far
  • Possibility to create different caches for different CSS styling 
  • Easy to use
  • Lightweight
  • Very fast 

I published the project on GitHub so from there you can download the latest version:

DEMO. Go and try it yourself!

In the demo you can notice how fast the elements with ellipsised text are displayed.
2000 elements generates in 0.6s !!!

Example usage

var myEllipsis = new FastEllipsis("font-family: arial; font-size: 10pt;");
var longText = "Some long text...";
var ellipsed = myEllipsis.ellipseIt(
  longText, // string to ellipsis
  2,        // maxline number 
  200       // width of container

Firstly you create instance of FastEllipsis object with custom styling of the text, so if you want to use FastEllipsis for more than one text styling you just create another object instance with the different styling as param.

Now you use ellipseIt() method with parameters showed on above code snippet: input string, maximum lines number and the width of container in px, and that's it!

At the end use normal jQuery.html() method to insert ellipsised variable into the div.

You don't need to create new object every time when you want to use FastEllipsis - for one text styling you create only one object where the cache is stored and then uyou use ellipseIt() method of this object as many times as you want.