changeset 141:2a2078bd334c

Optimise Javascript for adding line numbers Decreased the number of DOM manipulations and changed the $.each() into a regular for loop. It was taking an unreasonable amount of time for code snippets several hundred lines long.
author dellsystem <ilostwaldo@gmail.com>
date Fri, 12 Oct 2012 22:13:04 -0400
parents 3c4dc3b15f3b
children c3c4aaccbcd0
files static/js/agora.js
diffstat 1 files changed, 10 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/static/js/agora.js
+++ b/static/js/agora.js
@@ -43,14 +43,20 @@
         // Add in the line numbers (no JS fallback unfortunately)
         if ($('.snippet').length) {
             var counter = 1;
+            var lineNumbers = [];
 
-            $('.code-lines').children().each(function () {
+            var lines = $('.code-lines').children();
+
+            for (var i = 0, numLines = lines.length; i < numLines; i++) {
+                var line = lines[i];
                 // Set the top offset to be the same as that of the line
-                var div = '<p style="top: ' + this.offsetTop + 'px">' +
+                var div = '<p style="top: ' + line.offsetTop + 'px">' +
                     '<a href="#l' + counter + '">' + counter + '</a></p>';
                 counter++;
-                $('.line-counters').append(div);
-            });
+                lineNumbers.push(div);
+            }
+
+            $('.line-counters').append(lineNumbers.join(''));
         }
 
         // Highlight the code when the link is clicked