RMinelli
RMinelli

Reputation: 191

Syntax highlighting of dynamically generated snippet in web page using Prettify is slow

I've a div in which I dynamically load a piece of code from the result of an AJAX request. Then I want to format it using prettify. It works but it's damn slow. The code I use is the following:

var jqxhr = $.get(fileName)
 .success(function(data) {
  $('#myDiv').html(data);
  prettyPrint();
  $('#myDiv').fadeIn();
})

In short I do the GET request, I put the result of the request in #myDiv, I format it and I fadeIn the div. It takes a while but loads. But when I fade out the div then the page remains unresponsive for a couple of seconds. I removed the prettyPrint() and the page behaves just perfectly. Any hint?

Upvotes: 4

Views: 1591

Answers (1)

Marius Kjeldahl
Marius Kjeldahl

Reputation: 6824

I'm just speculating, but a couple of things worth mentioning.

According to the source, the default mode of prettify.js is to run using continuations, and to avoid hogging the CPU for more than 250ms a time (I'm quoting from the source at http://code.google.com/p/google-code-prettify/source/browse/trunk/src/prettify.js):

/**
 * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
 * UI events.
 * If set to {@code false}, {@code prettyPrint()} is synchronous.
 */
window['PR_SHOULD_USE_CONTINUATION'] = true;

The way you wrote your code above, indicate that it may be configured to run in a synchronous mode, which is why it's slow and hogging your page. You should make sure that this flag is not set to false, and add your fadeIn call in a callback function that you pass into the call to prettyPrint.

Assuming I've understood it correctly, if you manage to run prettyPrint in async mode, it should hog at most 250ms at the time, and by placing your call to fadeIn in a callback function passed to the call in prettyPrint, it will not fade it in until all syntax highlighting is done. If the series of calls to prettyPrint (250ms) at the time still feels slow, other suggestions may be to decrease the max time value to something less than 250, or alternatively figure out how to make sure prettyPrint ONLY prettyPrints the elements that got updated from your ajax call.

Upvotes: 3

Related Questions