1

I'm using this code now, works great except that it makes three requests to the webserver:

var refreshspeed=1000

        function moreSnow() {
    $("#uptimedynamic").load("index.html #uptimedynamic");
    $("#cpuloaddynamic").load("index.html #cpuloaddynamic");
    $("#meminfodynamic").load("index.html #meminfodynamic");
    setTimeout("moreSnow()", refreshspeed);
    }

Can someone tell me how to make it do the same thing, but with only one read of index.html? It needs to stay in the same repeating loop setup :)

Bo Persson
  • 90,663
  • 31
  • 146
  • 203

1 Answers1

0

This should do it

/* cache selectors in main page to avoid searching for them every second*/
var $upTime=$("#uptimedynamic"),  $cpuload = $("#cpuloaddynamic"), $meminfo=$("#meminfodynamic")


function moreSnow() {
    $.get("index.html", function(data){
        /* create a jQuery object from the retrieved page html that can then be traversed*/
        var $data=$(data);

        $upTime.html( $data.find('#uptimedynamic').html() );
        $cpuload.html( $data.find("#cpuloaddynamic").html() );
        $meminfo.html( $data.find("#meminfodynamic").html() );

    });
}

By retrieving only the contents of each element you alsoo avoid dupicating ID's in page and potential style issues

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Ok, I put that code on my page, but it doesn't loop like my original block. I tried to fit it into my existing loop but it won't work. Can you add in my loop to your code or let me know where exactly to fit your code into my loop? – Jamie Maunder Dec 25 '12 at 07:22
  • it is just the contents of the `moreSnow()` function...answer updated. I hadn't noticed this happens every second... let me modify a bit to cache some selectors – charlietfl Dec 25 '12 at 07:26
  • Woot, thanks!! Using this, it worked flawlessly: `function moreSnow() { $.get("index.html", function(data){ /* create a jQuery object from the retrieved page html that can then be traversed*/ var $data=$(data); $("#uptimedynamic").html( $data.find('#uptimedynamic').html() ); $("#cpuloaddynamic").html( $data.find("#cpuloaddynamic").html() ); $("#meminfodynamic").html( $data.find("#meminfodynamic").html() ); }); setTimeout("moreSnow()", refreshspeed); } ` – Jamie Maunder Dec 25 '12 at 07:28
  • OK..I modified slightly to cache selectors – charlietfl Dec 25 '12 at 07:30
  • Ok, I tried the updated "cached" code but it doesn't work. It appears to function fine, but the values never change. The index.html file I'm reading from IS the current page being displayed (i.e. the same page the scripts are running on! I know, it's weird, don't ask), so I'm thinking that's why it's not working? – Jamie Maunder Dec 25 '12 at 07:36