Question

I created the function below, which basically parses the HTML of a given url, scans for a certain class and process the text that it finds:

A small sample of my function:

function displayRating(theID){
  var $theUrl = $('#' + theID + ' > a').attr('href');
  jQuery.support.cors = true;
  var num, str, nums=[], avgnum, avgstr, avgnums=[];
  $.ajax({
    url: $theUrl,
    type: "GET",
    timeout: 3000,
    dataType: "text",
    success: function(data) {
      $(data).find(".count").each(function () {
        str = $(this).text();
        num = parseInt(str.substring(1,str.length-1), 10);
        nums.push(num);
      });
      var totalSum = 0;
      for (var i = 0; i < nums.length; i++){
        totalSum += nums[i];
      }
     more code here...
  });
}

I call this function 15 times because I need to display several data that can be collected from several pages. With this method, I was hoping that the number of http requests would be the same as the number that the function is called (15). However, I get an extremely huge number (340), which means that when parsing the HTML it also requests at the background all images that are included in the urls I call. This means that the loading time of the page is not acceptable (5-6 seconds).

My question is: Can I optimize this function so that it reads the HTML as plain text without loading at the background all images? Is there any way to minimize these requests?

Note: Unfortunately, PHP is not an option.

Was it helpful?

Solution

You could replace the src attribut with a custom one, parse the new string and than replace the right src tag:

data=data.replace(/ src=/g," mySrc=");
$(data).find(".count")...
...
data = data.replace(/ mySrc=/g," src=");

Here is a JSfiddle using (but not loading) your profile image.

N.B. you should usa a custom attribut (mySrc in the example) not found anyware in the data string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top