Javascript reusable images caching? - javascript

Is it possible to avoid asking server for 304 header for reusable images via jQuery or clean javascript?
Thanks ;)

The HTTP image caching is done between webserver and webbrowser. You won’t be able to influence it with JavaScript, as the expiration/modification headers are HTTP headers, which will be handled by the browser, and not passed to JavaScript.

You could try saving the images as javascript objects, ie.
var image = new Image();
image.src = "/test.png";
You can inject this object in the DOM as many times as you want and it will only request the image once.

Related

Proxy any request over a ws socket using plain javascript

I want to proxy any possible request from a webpage using a websocket connection.
I've resolved this in ajax environment implementing a custom XHRHttpRequest.
For each link I remove the href destination (or set it to '#') and set an onclick event.
What can I do with the img tags?
Thanks
Nothing.
By the time your javascript executes, probably the IMG.src resolution is already in course.
You may add the src as data-src instead and then have some javascript code that either set the src attribute or get the image through the websocket.
But, why are you doing this? Request multiplexing is part of the HTTP2 spec. You should stick to common HTTP1.x practices for the moment like bundling CSS and JS, image sprite, image compression, leveraging HTTP caching, etc.. etc... Doing something like that you are going to get into big complexity.

Force image caching with javascript

I am trying to clone an image which is generated randomly.
Although I am using the exact same url a different image is load. (tested in chrome and firefox)
I can't change the image server so I am looking for a pure javascript/jQuery solution.
How do you force the browser to reuse the first image?
Firefox:
Chrome:
Try it yourself (maybe you have to reload it several times to see it)
Code:
http://jsfiddle.net/TRUbK/
$("<img/>").attr('src', img_src)
$("<div/>").css('background', background)
$("#source").clone()
Demo:
http://jsfiddle.net/TRUbK/embedded/result/
You can't change the image server if it isn't yours, but you can trivially write something on your own server to handle it for you.
First write something in your server-side language of choice (PHP, ASP.NET, whatever) that:
Hits http://a.random-image.net/handler.aspx?username=chaosdragon&randomizername=goat&random=292.3402&fromrandomrandomizer=yes and downloads it. You generate a key in one of two way. Either get a hash of the whole thing (MD5 should be fine, it's not a security-related use so worries that it's too weak these days don't apply). Or get the size of the image - the latter could have a few duplicates, but is faster to produce.
If the image isn't already stored, save it in a location using that key as part of its filename, and the content-type as another part (in case there's a mixture of JPEGs and PNGs)
Respond with an XML or JSON response with the URI for the next stage.
In your client side-code, you hit that URI through XmlHttpRequest to obtain the URI to use with your images. If you want a new random one, hit that first URI again, if you want the same image for two or more places, use the same result.
That URI hits something like http://yourserver/storedRandImage?id=XXX where XXX is the key (hash or size as decided above). The handler for that looks up the stored copies of the images, and sends the file down the response stream, with the correct content-type.
This is all really easy technically, but the possible issue is a legal one, since you're storing copies of the images on another server, you may no longer be within the terms of your agreement with the service sending the random images.
You can try saving the base64 representation of the image.
Load the image in an hidden div/canvas, then convert it in base64. (I'm not sure if a canvas can be hidden, nor if it is possible to convery the img using html4 tag)
Now you can store the "stringified" image in a cookie, and use it unlimited times...
The headers being sent from your random image generator script include a Cache-Control: max-age=0 declaration which is in essence telling the browser not to cache the image.
You need to modify your image generator script/server to send proper caching headers if you want the result to be cached.
You also need to make sure that the URL stays the same (I didn't look at that aspect since there were tons of parameter being passed).
There seems to be two workarounds:
If you go with the Canvas method, see if you can get the image to load onto the Canvas itself so that you can manipulate the image data directly instead of making a 2nd http request for the image. You can feed the image data directly onto a 2nd Canvas.
If you're going to build a proxy, you can have the proxy remove the No-Cache directive so that subsequent requests by your browser use the cache (no guarantees here - depends on browser/user settings).
First off, you can "force" anything on the web. If you need to force things, then web development is the wrong medium for you.
What you could try, is to use a canvas element to copy the image. See https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images for examples.
Tell it to stop getting a random image, seems to work the way you want when I add this third replace call:
// Get the canvas element.
var background = ($("#test").css('background-image')),
img_src = background.replace(/^.+\('?"?/, '').replace(/'?"?\).*$/, '').replace(/&fromrandomrandomizer=yes/,'')
try:
var myImg = new Image();
myImg.src = img_src;
and then append "myImg" to where you want:
$(document).append(myImg);
I did this with your fiddler scripts and got the same image every time
#test {
background:url(http://a.random-image.net.nyud.net/handler.aspx?username=chaosdragon&randomizername=goat&random=292.3402&fromrandomrandomizer=yes);
width: 150px;
height: 150px;
}
note the .nyud.net after the domain name.

Javascript bottleneck for server communication (for downloading resources)

I'm writing a javascript application. In my application I want to create my own cache management.
Now my question is: Is there any bottleneck in javascript (e.g. any event on window object) that we can handle and modify all server communications?
many tags in the page can request a resource from server e.g. img, link, script.
In other words I want a bottleneck in javascript that I can be notified that a resource is requested from server. Then I will look into my cache-system and will serve the resource either from my cache or by downloading the content from a generic HTTP handler on my server.
I know it's a bit strange requirement but because I believe javascript is very flexible I though this "bottleneck" may exist.
Thank you.
One way to lazy load resources is to set a common source (eg. 1.gif for images, x.txt for script/css) pointing at small, cacheable resources. Then set a data attribute on the element with the actual path to the content.
<img src="/1.gif" data-url="/images/puppies.png" class="onhold" />
Finally, on domready or document load you could do your logic to set the proper urls, replace dom element, etc. Using jQuery you'd do something like this -
jQuery(document).ready(function($){
$("img.onhold").each(function() {
var img = $(this),
url = img.data("url");
// any logic to update url based on cache, CDN, etc. here
img.attr("src", url);
});
});

Return image from HTTP Post request in Javascript

I send data from a browser to a servlet using JavaScript, then the server processes the data and returns an image as a response (all using xmlhttprequest). I'm sure everything is working fine because when I call the server directly, I get my image back in the browser.
What I was wondering is how, in JavaScript, do I parse my response so that I can display it as an image in an img tag?
I figure this should be fairly easy, but not sure how to do it.
You could use data URIs and set the base64 encoded binary data as the src for an image tag.
If you have control over the server, it might be cleaner to have the server give you a URL you can refer to and create a new img tag with that src.
Not sure if this would work with your application, but you could use a server-side script to dynamically serve an image, and then just use javascript to change the source of your image.
i.e.
src="image.php?param1=XXXX&param2=XXXX"
Or just have your XMLHttpRequest return a new path to an existing image on the server and then just change the src attribute of your img.

Is it possible to download image using Ajax

I know we can request xml, html as well as text images directly using ajax but can we request files like image, zip etc. using Ajax. How ?
Ajax just means "Making an HTTP request from JavaScript without leaving the page", so yes.
You can't do much that is useful with a zip file or an image if you fetch it with XMLHttpRequest though.
Images can be added to the document by simply generating a new <img> element.
It might help if you provided more information about what you were trying to achieve. It sounds like an xy problem.
You could transport the image over an xmlRequest as base64, but since base64 is ~30% larger it will have some impact on your speed.
Yes, you can do so. Actually the same ajax principles apply here too. You use a server-side language to download a file.

Categories