jQuery $.get() Memory Usage - javascript

This is the jQuery method that I have at my webpage, it refreshes a image every 5 seconds by loading the same page and replacing the image.
$(document).ready(function () {
var refreshId = setInterval(function () {
$.get('default.aspx', function (data) {
var page = data;
var image = $(page).find("img");
var fecha = $(page).find("div #fecha");
$("#Chart1").attr("src", image.attr("src"));
$("#fecha").text(fecha.text());
});
}, 5000);
});
I saw that everytime it loads the img, the data get stored somewhere in the browser and it doesnt cleans.. And when I open the task manager, I can see the memory usage growing up..
and heres a screenshot of the image axd..
Should I worry about freeing memory? Or everything is working as its supposed to..

why not reload the image by using just the url and not fetch the whole page that gets the url? if you want to prevent cache, either set the image not to cache via server headers, or use cachebusting
var img = document.getElementById('Chart1'); //use plain JS since it's just an ID
var refreshId = setInterval(function () {
var rand = "?"+(Math.random()*10000000000000000); //cache busting method
img.src = "path_to_image"+rand //set src using busted url
}, 5000);
this will still eat up disk space since each busted images is treated like a different image. if it were cached, you'd be using stale images. but at least you are not loading the whole page again an again.

Found out that the browser is just caching the images, but they are being cleaned eventually.

Use $post instead of $get. IE often cash GET request data.

There is just one img#Chart1 in your page, so there is only one image uses memory.
Others would just in the browser's cache.
But I don't think that default.aspx return in html format,
it should return data in json like:
{
imageUrl: "http://example.com/a.jpg",
fetcha: "some text"
}

Related

Javascript: How to check if image is already cached

I just started to learn a little bit of JavaScript and i wondered if there is a way to check if an image is already loaded to cache.
In my script im loading some random images from another webpage and display them.
When the same image will be displayed the second time, the script won't use the already loaded image, but instead load the same image again, so that there are two of them stored in my cache.
Now I want to check if the image is already stored in cache and if so, use the cached one instead of loading it again.
My code:
<script>
var img = document.createElement('img');
var index;
//On Click create random 3digit number between 1 and 100
document.getElementById('image').onclick = function(){
var index = '' + Math.floor(Math.random() * 100 +1);
while(index.length < 3) {
index = '0' + index;
}
loadImages(index);
};
//Load the image with the created number
function loadImages(id) {
var src = 'someWebPage/' + id +'.png';
img.onload = function () {
document.getElementById('image').getContext("2d").drawImage(img, 0, 0, 300, 300);
}
img.src = src;
}
</script>
Picture of my cache:
As you can see 030.png and 032.png are twice in cache.
Hope you can give me some advice.
EDIT:
Just for anyone else that faces this problem, it actually isnĀ“t one at all.
Chrome already did everything right, i only did not notice.
As you can see in the column Size the pictures were already loaded from my cache.
The way caching (in this context) is handled is by the browser negotiating with the server using a set of headers to basically tell the server "I already have this version of this resource", to which the server can then respond "OK, that is still valid, no need to download anything new". So you shouldn't be concerned about the caching in the JavaScript side, but instead make sure you are setting the correct Cache-Control headers on the server side. There are likely already questions/answers for your server/framework of choice on how to setup the caching there.

Background image not changing from javascript

I am working on a project related to image processing. Currently, I am taking a image from the webcam and saving it in some folder. Then I display that image as a background image on the div. This works fine. But when I take the image again, the background image still remains the same. But when I see the image in the folder, it has changed.
Note: Both the images are saved by same name. So, previous image is just replaced by current image. And the image is taken by clicking a button.
html code:
<button id = "click" onclick = "mooddetect()">MOODY</button>
function mooddetect() {
$.ajax({
url: '/mooddetect/',
type:"POST",
cache:false,
success: function(input) {
var x = document.getElementById('photo');
x.style.backgroundImage = "url('/static/detect/test.jpg')";
},
failure: function(data) {
alert('Got an error dude');
}
});
}
views.py:
def get_image(camera):
retval, im = camera.read()
return im
def webcam():
camera_port = 0
ramp_frames = 30
camera = cv2.VideoCapture(camera_port)
for i in xrange(ramp_frames):
temp = get_image(camera)
print("Taking image...")
camera_capture = get_image(camera)
file = "./music/static/detect/test.jpg"
cv2.imwrite(file, camera_capture)
del(camera)
#csrf_exempt
def mooddetect(request):
webcam()
return HttpResponse("success")
UPDATE 2 - check this question for more info and better ways to acheive that: Refresh image with a new one at the same url
UPDATE:
What helped was saving the images with a new name and send the updated url to the front, as i assumed it have to do with cache, but im not sure why adding ?c=rand didn't helped.
I assume it will have to do with the cache of the browser.
Try to add timestamp or other rand number to the image url, so you will force to load the new image every time.
x.style.backgroundImage = "url('/static/detect/test.jpg?c=|some random number|')";
you can read more: how to clear or replace a cached image
Try this to clear the cache:
x.style.backgroundImage = `url('/static/detect/test.jpg?${Date.now()}')`

Html2canvas: facebook plugin comments

I have a website witch uses facebook plugin comments. I'm looking for a way to have those comments inside a screenshot. If I use the simple html2canvas I get a blank box instead of them. So I try to use html2canvasproxy but now it print some javascript console log instead of the facebook comments.
It shoud be like but I get . I noticed that the html2canvasproxy.php saves the facebook plugin html correctly.
I can't find any javascript error in the console log.
I'm using the following code to take the screenshot:
html2canvas(document.body, {
"logging": true, //Enable log (use Web Console for get Errors and Warnings)
"proxy":"js/html2canvasproxy.php",
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
document.body.appendChild(img);
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
And I have this settings in html2canvasproxy.php:
//Turn off errors because the script already own uses "error_get_last"
error_reporting(0);
//setup
define('JSLOG', 'console.log'); //Configure alternative function log, eg. console.log, alert, custom_function
define('PATH', '../screenshots');//relative folder where the images are saved
define('CCACHE', 60 * 5 * 1000);//Limit access-control and cache, define 0/false/null/-1 to not use "http header cache"
define('TIMEOUT', 30);//Timeout from load Socket
define('MAX_LOOP', 10);//Configure loop limit for redirect (location header)
define('CROSS_DOMAIN', 0);//Enable use of "data URI scheme"
//constants
define('EOL', chr(10));
define('WOL', chr(13));
define('GMDATECACHE', gmdate('D, d M Y H:i:s'));
First idea I got while reading is to include some timeout - waiting a bit longer (let's say 200ms) - so that you have more probability for things to get loaded.
But after reading this on plugin site: "The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page." it could not help.
Personally I would investigate using another solution - like for example PhantomJS:
"PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG."
It's easy like this:
var page = require('webpage').create();
page.open('http://github.com/', function() {
page.render('github.png');
phantom.exit();
});

fetch image url at fixed intervals using javascript

I am a complete beginner in javascript so I don't even know where to begin. I have a URL that displays a .jpg snapshot. It is served from a video server. I would like to take the image and display it on a webpage with the image being refreshed every 2 seconds. The image will be displayed in a div container with id="snapshot"
Any help or guidance will be greatly appreciated.
For your html, you do the following:
<div id="snapshot"><img/></div>
Then in your JavaScript you do the following:
var url = "some url somewhere";
var snapshotImg = document.querySelector('#snapshot > img');
var updateInterval = setInterval(updateImage, 2000); //start the update every 2 seconds
updateImage(); //immediately update the image
function updateImage(){
snapshotImg.src = url + "?"+ new Date().getTime();
}
In the 'updateImage' function, I added a ? and a time hash to the url so that each time it sets the source, the srcurl is unique. If you don't make it unique each time, the browser will cache the image from the first request, and it won't ever update the image. So, you have to make the url unique, and you that by adding a hash, that is arbitrary, to the end of the url. I hope that makes sense.

jQuery - Read data from text file with .get/.load - force reload?

I want to load data from a web server with jQuery. I'm uploading a file to a web server, put the response (which is containing a link) to an iframe and read this link with .get(). When I now upload another file, which leads to the same filename but changed contents, .get() does not read the content correctly on the first try, but reliable on the second. .load() should do basically the same, but does not reload the file no matter how often I re-upload the file.
Is there a chance to force the reload of the changed file?
var linkToTextFile = 'http://www.myserver.com/myTextFile.txt';
$.get(linkToTextFile, function(data){
alert("Data:" + data); //content changes on second try
});
Try to append a random GET parameter to your text file's URL :
var timestamp = new Date().getTime();
var linkToTextFile = 'http://www.myserver.com/myTextFile.txt?t=' + timestamp;
This way it will force the browser to reload the file.

Categories

Resources