Why do browsers inefficiently make 2 requests here? - javascript
I noticed something odd regarding ajax and image loading. Suppose you have an image on the page, and ajax requests the same image - one would guess that ajax requests would hit the browser cache, or it should at least only make one request, the resulting image going to the page and the script that wants to read/process the image.
Surprisingly, I found that even when the javascript waits for the entire page to load, the image request still makes a new request! Is this a known bug in Firefox and Chrome, or something bad jQuery ajax is doing?
Here you can see the problem, open Fiddler or Wireshark and set it to record before you click "run":
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<div id="something" style="background-image:url(http://jsfiddle.net/img/logo-white.png);">Hello</div>
<script>
jQuery(function($) {
$(window).load(function() {
$.get('http://jsfiddle.net/img/logo-white.png');
})
});
</script>
Note that in Firefox it makes two requests, both resulting in 200-OK, and sending the entire image back to the browser twice. In Chromium, it at least correctly gets a 304 on second request instead of downloading the entire contents twice.
Oddly enough, IE11 downloads the entire image twice, while it seems IE9 aggressively caches it and downloads it once.
Ideally I would hope the ajax wouldn't make a second request at all, since it is requesting exactly the same url. Is there a reason css and ajax in this case usually have different caches, as though the browser is using different cache storage for css vs ajax requests?
I use the newest Google Chrome and it makes one request. But in your JSFIDDLE example you are loading jQuery twice. First with CSS over style attribute and second in your code over script tag. Improved: JSFIDDLE
<div id="something" style="background-image:url('http://jsfiddle.net/img/logo-white.png');">Hello</div>
<script>
jQuery(window).load(function() {
jQuery.get('http://jsfiddle.net/img/logo-white.png');
});
// or
jQuery(function($) {
jQuery.get('http://jsfiddle.net/img/logo-white.png');
});
</script>
jQuery(function($) {...} is called when DOM is ready and jQuery(window).load(...); if DOM is ready and every image and other resources are loaded. To put both together nested makes no sense, see also here: window.onload vs $(document).ready()
Sure, the image is loaded two times in Network tab of the web inspector. First through your CSS and second through your JavaScript. The second request is probably cached.
UPDATE: But every request if cached or not is shown in this tab. See following example: http://jsfiddle.net/95mnf9rm/4/
There are 5 request with cached AJAX calls and 5 without caching. And 10 request are shown in 'Network' tab.
When you use your image twice in CSS then it's only requested once. But if you explicitly make a AJAX call then the browser makes an AJAX call. As you want. And then maybe it's cached or not, but it's explicitly requested, isn't it?
This "problem" could a be a CORS pre-flight test.
I had noticed this in my applications awhile back, that the call to retrieve information from a single page application made the call twice. This only happens when you're accessing URLs on a different domain. In my case we have APIs we've built and use on a different server (a different domain) than that of the applications we build. I noticed that when I use a GET or POST in my application to these RESTFUL APIs the call appears to be made twice.
What is happening is something called pre-flight (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS), an initial request is made to the server to see if the ensuing call is allowed.
Excerpt from MDN:
Unlike simple requests, "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
Your fiddle tries to load a resource from another domain via ajax:
I think I created a better example. Here is the code:
<img src="smiley.png" alt="smiley" />
<div id="respText"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(window).load(function(){
$.get("smiley.png", function(){
$("#respText").text("ajax request succeeded");
});
});
</script>
You can test the page here.
According to Firebug and the chrome network panel the image is returned with the status code 200 and the image for the ajax request is coming from the cache:
Firefox:
Chrome:
So I cannot find any unexpected behavior.
Cache control on Ajax requests have always been a blurred and buggy subject (example).
The problem gets even worse with cross-domain references.
The fiddle link you provided is from jsfiddle.net which is an alias for fiddle.jshell.net. Every code runs inside the fiddle.jshell.net domain, but your code is referencing an image from the alias and browsers will consider it a cross-domain access.
To fix it, you could change both urls to http://fiddle.jshell.net/img/logo-white.png or just /img/logo-white.png.
The helpful folks at Mozilla gave some details as to why this happens. Apparently Firefox assumes an "anonymous" request could be different than normal, and for this reason it makes a second request and doesn't consider the cached value with different headers to be the same request.
https://bugzilla.mozilla.org/show_bug.cgi?id=1075297
This may be a shot in the dark, but here's what I think is happening.
According to,
http://api.jquery.com/jQuery.get/
dataType
Type: String
The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, or html).
Gives you 4 possible return types. There is no datatype of image/gif being returned. Thus, the browser doesn't test it's cache for the src document as it is being delivered a a different mime type.
The server decides what can be cached and for how long. However, it again depends on the browser, whether or not to follow it. Most web browsers like Chrome, Firefox, Safari, Opera and IE follow it, though.
The point that I want to make here, is that your web sever might be configured to not allow your browser to cache the content, thus, when you request the image through CSS and JS, the browser follows your server's orders and doesn't cache it and thus it requests the image twice...
I want JS-accessible image
Have you tried to CSS using jQuery? It is pretty fun - you have full CRUD (Create, read, update, delete) CSS elements. For example do image resize on server side:
$('#container').css('background', 'url(somepage.php?src=image_source.jpg'
+ '&w=' + $("#container").width()
+ '&h=' + $("#container").height() + '&zc=1');
Surprisingly, I found that even when the javascript waits for the entire page to load, the image request still makes a new request! Is this a known bug in Firefox and Chrome, or something bad jQuery ajax is doing?
It is blatantly obvious that this is not a browser bug.
The computer is deterministic and does what exactly you tell it to (not want you want it to do). If you want to cache images it is done in server side. Based on who handles caching it can be handled as:
Server (like IIS or Apache) cache - typically caches things that are reused often (ex: 2ce in 5 seconds)
Server side application cache - typically it reuses server custom cache or you create sprite images or ...
Browser cache - Server side adds cache headers to images and browsers maintain cache
If it is not clear then I would like to make it clear : You don't cache images with javascript.
Ideally I would hope the ajax wouldn't make a second request at all, since it is requesting exactly the same url.
What you try to do is to preload images.
Once an image has been loaded in any way into the browser, it will be
in the browser cache and will load much faster the next time it is
used whether that use is in the current page or in any other page as
long as the image is used before it expires from the browser cache.
So, to precache images, all you have to do is load them into the
browser. If you want to precache a bunch of images, it's probably best
to do it with javascript as it generally won't hold up the page load
when done from javascript. You can do that like this:
function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
for (var i = 0; i < array.length; i++) {
var img = new Image();
img.onload = function() {
var index = preloadImages.list.indexOf(this);
if (index !== -1) {
// remove this one from the array once it's loaded
// for memory consumption reasons
preloadImages.splice(index, 1);
}
}
preloadImages.list.push(img);
img.src = array[i];
}
}
preloadImages(["url1.jpg", "url2.jpg", "url3.jpg"]);
Then, once they've been preloaded like this via javascript, the browser will have them in its cache and you can just refer to the normal URLs in other places (in your web pages) and the browser will fetch that URL from its cache rather than over the network.
Source : How do you cache an image in Javascript
Is there a reason css and ajax in this case usually have different caches, as though the browser is using different cache storage for css vs ajax requests?
Even in absence of information do not jump to conclusions!
One big reason to use image preloading is if you want to use an image
for the background-image of an element on a mouseOver or :hover event.
If you only apply that background-image in the CSS for the :hover
state, that image will not load until the first :hover event and thus
there will be a short annoying delay between the mouse going over that
area and the image actually showing up.
Technique #1 Load the image on the element's regular state, only shift it away with background position. Then move the background
position to display it on hover.
#grass { background: url(images/grass.png) no-repeat -9999px -9999px; }
#grass:hover { background-position: bottom left; }
Technique #2 If the element in question already has a background-image applied and you need to change that image, the above
won't work. Typically you would go for a sprite here (a combined
background image) and just shift the background position. But if that
isn't possible, try this. Apply the background image to another page
element that is already in use, but doesn't have a background image.
#random-unsuspecting-element {
background: url(images/grass.png) no-repeat -9999px -9999px; }
#grass:hover { background: url(images/grass.png) no-repeat; }
The idea create new page elements to use for this preloading technique
may pop into your head, like #preload-001, #preload-002, but that's
rather against the spirit of web standards. Hence the using of page
elements that already exist on your page.
The browser will make the 2 requests on the page, cause an image called from the css uses a get request (not ajax) too before rendering the entire page.
The window load is similar to de attribute, and is loading before the rest of the page, then, the image from the Ajax will be requested first than the image on the div, processed during the page load.
If u would like to load a image after the entire page is loaded, u should use the document.ready() instead
Related
How can I cancel consecutive requests to my server? [duplicate]
What would cause a page to be canceled? I have a screenshot of the Chrome Developer Tools. This happens often but not every time. It seems like once some other resources are cached, a page refresh will load the LeftPane.aspx. And what's really odd is this only happens in Google Chrome, not Internet Explorer 8. Any ideas why Chrome would cancel a request?
We fought a similar problem where Chrome was canceling requests to load things within frames or iframes, but only intermittently and it seemed dependent on the computer and/or the speed of the internet connection. This information is a few months out of date, but I built Chromium from scratch, dug through the source to find all the places where requests could get cancelled, and slapped breakpoints on all of them to debug. From memory, the only places where Chrome will cancel a request: The DOM element that caused the request to be made got deleted (i.e. an IMG is being loaded, but before the load happened, you deleted the IMG node) You did something that made loading the data unnecessary. (i.e. you started loading a iframe, then changed the src or overwrite the contents) There are lots of requests going to the same server, and a network problem on earlier requests showed that subsequent requests weren't going to work (DNS lookup error, earlier (same) request resulted e.g. HTTP 400 error code, etc) In our case we finally traced it down to one frame trying to append HTML to another frame, that sometimes happened before the destination frame even loaded. Once you touch the contents of an iframe, it can no longer load the resource into it (how would it know where to put it?) so it cancels the request.
status=canceled may happen also on ajax requests on JavaScript events: <script> $("#call_ajax").on("click", function(event){ $.ajax({ ... }); }); </script> <button id="call_ajax">call</button> The event successfully sends the request, but is is canceled then (but processed by the server). The reason is, the elements submit forms on click events, no matter if you make any ajax requests on the same click event. To prevent request from being cancelled, JavaScript event.preventDefault(); have to be called: <script> $("#call_ajax").on("click", function(event){ event.preventDefault(); $.ajax({ ... }); }); </script>
NB: Make sure you don't have any wrapping form elements. I had a similar issue where my button with onclick={} was wrapped in a form element. When clicking the button the form is also submitted, and that messed it all up...
Another thing to look out for could be the AdBlock extension, or extensions in general. But "a lot" of people have AdBlock.... To rule out extension(s) open a new tab in incognito making sure that "allow in incognito is off" for the extention(s) you want to test.
In my case, I found that it is jquery global timeout settings, a jquery plugin setup global timeout to 500ms, so that when the request exceed 500ms, chrome will cancel the request.
You might want to check the "X-Frame-Options" header tag. If its set to SAMEORIGIN or DENY then the iFrame insertion will be canceled by Chrome (and other browsers) per the spec. Also, note that some browsers support the ALLOW-FROM setting but Chrome does not. To resolve this, you will need to remove the "X-Frame-Options" header tag. This could leave you open to clickjacking attacks so you will need to decide what the risks are and how to mitigate them.
Here's what happened to me: the server was returning a malformed "Location" header for a 302 redirect. Chrome failed to tell me this, of course. I opened the page in firefox, and immediately discovered the problem. Nice to have multiple tools :)
Another place we've encountered the (canceled) status is in a particular TLS certificate misconfiguration. If a site such as https://www.example.com is misconfigured such that the certificate does not include the www. but is valid for https://example.com, chrome will cancel this request and automatically redirect to the latter site. This is not the case for Firefox. Currently valid example: https://www.pthree.org/
A cancelled request happened to me when redirecting between secure and non-secure pages on separate domains within an iframe. The redirected request showed in dev tools as a "cancelled" request. I have a page with an iframe containing a form hosted by my payment gateway. When the form in the iframe was submitted, the payment gateway would redirect back to a URL on my server. The redirect recently stopped working and ended up as a "cancelled" request instead. It seems that Chrome (I was using Windows 7 Chrome 30.0.1599.101) no longer allowed a redirect within the iframe to go to a non-secure page on a separate domain. To fix it, I just made sure any redirected requests in the iframe were always sent to secure URLs. When I created a simpler test page with only an iframe, there was a warning in the console (which I had previous missed or maybe didn't show up): [Blocked] The page at https://mydomain.com/Payment/EnterDetails ran insecure content from http://mydomain.com/Payment/Success The redirect turned into a cancelled request in Chrome on PC, Mac and Android. I don't know if it is specific to my website setup (SagePay Low Profile) or if something has changed in Chrome.
Chrome Version 33.0.1750.154 m consistently cancels image loads if I am using the Mobile Emulation pointed at my localhost; specifically with User Agent spoofing on (vs. just Screen settings). When I turn User Agent spoofing off; image requests aren't canceled, I see the images. I still don't understand why; in the former case, where the request is cancelled the Request Headers (CAUTION: Provisional headers are shown) have only Accept Cache-Control Pragma Referer User-Agent In the latter case, all of those plus others like: Cookie Connection Host Accept-Encoding Accept-Language Shrug
I got this error in Chrome when I redirected via JavaScript: <script> window.location.href = "devhost:88/somepage"; </script> As you see I forgot the 'http://'. After I added it, it worked.
Here is another case of request being canceled by chrome, which I just encountered, which is not covered by any of answers up there. In a nutshell Self-signed certificate not being trusted on my android phone. Details We are in development/debug phase. The url is pointing to a self-signed host. The code is like: location.href = 'https://some.host.com/some/path' Chrome just canceled the request silently, leaving no clue for newbie to web development like myself to fix the issue. Once I downloaded and installed the certificate using the android phone the issue is gone.
If you use axios it can help you // change timeout delay: instance.defaults.timeout = 2500; https://github.com/axios/axios#config-order-of-precedence
For my case, I had an anchor with click event like <a href="" onclick="somemethod($index, hour, $event)"> Inside click event I had some network call, Chrome cancelling the request. The anchor has href with "" means, it reloads the page and the same time it has click event with network call that gets cancelled. Whenever i replace the href with void like <a href="javascript:void(0)" onclick="somemethod($index, hour, $event)"> The problem went away!
If you make use of some Observable-based HTTP requests like those built-in in Angular (2+), then the HTTP request can be canceled when observable gets canceled (common thing when you're using RxJS 6 switchMap operator to combine the streams). In most cases it's enough to use mergeMap operator instead, if you want the request to complete.
I had faced the same issue, somewhere deep in our code we had this pseudocode: create an iframe onload of iframe submit a form After 2 seconds, remove the iframe thus, when the server takes more than 2 seconds to respond the iframe to which the server was writing the response to, was removed, but the response was still to be written , but there was no iframe to write , thus chrome cancelled the request, thus to avoid this I made sure that the iframe is removed only after the response is over, or you can change the target to "_blank". Thus one of the reason is: when the resource(iframe in my case) that you are writing something in, is removed or deleted before you stop writing to it, the request will be cancelled
I have embedded all types of font as well as woff, woff2, ttf when I embed a web font in style sheet. Recently I noticed that Chrome cancels request to ttf and woff when woff2 is present. I use Chrome version 66.0.3359.181 right now but I am not sure when Chrome started canceling of extra font types.
We had this problem having tag <button> in the form, that was supposed to send ajax request from js. But this request was canceled, due to browser, that sends form automatically on any click on button inside the form. So if you realy want to use button instead of regular div or span on the page, and you want to send form throw js - you should setup a listener with preventDefault function. e.g. $('button').on('click', function(e){ e.preventDefault(); //do ajax $.ajax({ ... }); })
I had the exact same thing with two CSS files that were stored in another folder outside my main css folder. I'm using Expression Engine and found that the issue was in the rules in my htaccess file. I just added the folder to one of my conditions and it fixed it. Here's an example: RewriteCond %{REQUEST_URI} !(images|css|js|new_folder|favicon.ico) So it might be worth you checking your htaccess file for any potential conflicts
happened to me the same when calling a. js file with $. ajax, and make an ajax request, what I did was call normally.
In my case the code to show e-mail client window caused Chrome to stop loading images: document.location.href = mailToLink; moving it to $(window).load(function () {...}) instead of $(function () {...}) helped.
In can this helps anybody I came across the cancelled status when I left out the return false; in the form submit. This caused the ajax send to be immediately followed by the submit action, which overwrote the current page. The code is shown below, with the important return false at the end. $('form').submit(function() { $.validator.unobtrusive.parse($('form')); var data = $('form').serialize(); data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val(); if ($('form').valid()) { $.ajax({ url: this.action, type: 'POST', data: data, success: submitSuccess, fail: submitFailed }); } return false; //needed to stop default form submit action }); Hope that helps someone.
For anyone coming from LoopbackJS and attempting to use the custom stream method like provided in their chart example. I was getting this error using a PersistedModel, switching to a basic Model fixed my issue of the eventsource status cancelling out. Again, this is specifically for the loopback api. And since this is a top answer and top on google i figured i'de throw this in the mix of answers.
For me 'canceled' status was because the file did not exist. Strange why chrome does not show 404.
It was as simple as an incorrect path for me. I would suggest the first step in debugging would be to see if you can load the file independently of ajax etc.
The requests might have been blocked by a tracking protection plugin.
It happened to me when loading 300 images as background images. I'm guessing once first one timed out, it cancelled all the rest, or reached max concurrent request. need to implement a 5-at-a-time
One the reasons could be that the XMLHttpRequest.abort() was called somewhere in the code, in this case, the request will have the cancelled status in the Chrome Developer tools Network tab.
In my case, it started coming after chrome 76 update. Due to some issue in my JS code, window.location was getting updated multiple times which resulted in canceling previous request. Although the issue was present from before, chrome started cancelling request after update to version 76.
I had the same issue when updating a record. Inside the save() i was prepping the rawdata taken from the form to match the database format (doing a lot of mapping of enums values, etc), and this intermittently cancels the put request. i resolved it by taking out the data prepping from the save() and creating a dedicated dataPrep() method out of it. I turned this dataPrep into async and await all the memory intensive data conversion. I then return the prepped data to the save() method that i could use in the http put client. I made sure i await on dataPrep() before calling the put method: await dataToUpdate = await dataPrep(); http.put(apiUrl, dataToUpdate); This solved the intermittent cancelling of request.
Replacing entire page via AJAX causes Permission Denied error in IE only
I have an AJAX post that retrieves data from the server and either replaces part of the page or in some cases the full page. This is controlled by a javascript fullRefresh parameter. The problem is the refresh code works find in Firefox but causes a Permission Denied error in the bowels of JQuery after it runs in IE although it would appear to actually replace the page contents successfully. IE version 11.0.9600.16659 JQuery version 1.8.2 Error message Unhandled exception at line 2843, column 3 in http://localhost:62761/Scripts/jquery-1.8.2.js 0x800a0046 - JavaScript runtime error: Permission denied My code is function RefreshScreenContent(formActionUrl, formHTML, fullRefresh) { fullRefresh = (typeof fullRefresh === "undefined") ? false : fullRefresh; if (fullRefresh) { document.write(formHTML); document.close(); } else { $("#content-parent").html(formHTML); } } The partial refreshes work fine but the full refreshes are the problem. I have tried hardcoding the document.write call to write a well formed simple html page rather than formHTML in case that was somehow the problem but even a simple single word page causes the error. The actual error occurs a some point later with a callback inside JQuery. The AJAX post to the server is in the same application i.e. is not a cross domain request. I have seen posts online talking aboue cross domain stuff that is not applicable here. Can anyone tell me why this is happening and how to stop it? Is there an alternative IE way of replacing the page contents?
Your code is fine (at least at first glance). My guess is that you make the call in such a way, that it is interpreted as cross-domain. I would suggest checking: http vs https (most common) the destination port the root url maybe the "destination" page makes some requests of its own, check to be on same domain The reason why IE may be the only one with the problem is that it has higher security demanding by default that other browsers (check advanced security settings - can't remember where they are put in menu) so it interprets requests in a more "paranoid" manor. I repeat, what I said is just a guess, based on cases I've been put into.
In the end I used the approach here to replace the body tag in the pgae with the one in the markup the AJAX receives back https://stackoverflow.com/a/7839921/463967 I would have preferred to replace all content not just the body but I can always adapt later to include the header etc as body is enough for my uses right now. This works in IE and Firefox.
Force (or ask nicely) to refresh the browser
So I run a site that uses a lot of javascript and ajax. I understand how to make users refresh their browser when the browser loads. But what happens if I need them to refresh their browser after they have loaded the site? I want to change the ajax that is served to the client to speed up things up, but this is going to cause errors for the users who have not yet refreshed their browser. The only solution I can come up with is that when a new version of the JavaScript file is required, the site uses a popup that asks the users to force refresh their browsers. (This won't really fix the current version, but would prevent future issues.) I hate to use a popup for something that I could do automatically. Is there a better way to force updates for the client?
window.location.href = "http://example.com" replaces the current page with the one pointed to by http://example.com.
You sound like you are having trouble with your JavaScript getting an updated version of the data it loads through Ajax methods, is that correct? For instance, if two Ajax calls try to load 'data.txt', then the second call merely uses the cached version. You also may be having trouble with loading new versions your script itself. The way around both of these problems is to add a randomly-generated query string to your script source and your Ajax source. For example, make one script that loads your main script, like this: /* loader1.js */ document.write('<script src="mainjavascript.js?.rand=', Math.random(), '"></script>'); And in your HTML, just do <script src="loader1.js"></script> The same method works for JavaScript Ajax requests as well. Assuming that "client" is a new XMLHttpRequest() object, and has been properly set up with a readystatechange function and so on, then the you simply append the same query string, like this: request = client.open('GET', 'data.txt?.rand=' + Math.random(), true); request.send(); You may be using a library to do your Ajax requests, and so it's even easier then. Just specify the data URL as 'data.txt?.rand=' + Math.random() instead of merely 'data.txt'
Can I get the data of a cross-site <img/> tag as a blob?
I am trying to save a couple of images that are linked to by a webpage to offline storage. I'm using IndexedDB on Firefox and FileSystem API on Chrome. My code is actually an extension, so on Firefox I'm running on Greasemonkey, and on Chrome as a content script. I want this to be automated. I am running into problem when I retrieve the image file. I'm using example code from the article titled Storing images and files in IndexedDB, but I get an error: the images I'm trying to download are on a different subdomain and the XHR fails. XMLHttpRequest cannot load http://...uxgk.JPG. Origin http://subdomain.domain.com is not allowed by Access-Control-Allow-Origin. On Firefox I could probably use GM_xmlhttpRequest and it'd work (the code works on both browsers when I'm in same-origin URLs), but I still need to solve the problem for Chrome, in which other constraints (namely, needing to interact with frames on the host page) require me to incorporate my script in the page and forfeit my privileges. So it comes back to that I'm trying to figure out a way to save images that are linked to (and may appear in) the page to IndexedDB and/or FileSystem API. I either need to realize how to solve the cross-origin problem in Chrome (and if it requires privileges, then I need to fix the way I'm interacting with jQuery) or some kind of reverse createObjectURL. At the end of the day I need a blob (File object, as far as I understand) to put into the IndexedDB (Firefox) or to write to FileSystem API (Chrome) Help, anyone? Edit: my question may actually really come down to how I can use jQuery the way I want without losing my content script privileges on Chrome. If I do, I could use cross-origin XHRs on Chrome as well. Though I'd much rather get a solution that doesn't rely on that. Specifically since I'd like this solution if I get the script incorporated into the webpage, and not require it to be a content script/userscript. Edit: I realized that the question is only about cross-site requests. Right now I have one of three ways to get the image blob, with the help of #chris-sobolewski, these questions and some other pages (like this), which can be seen in this fiddle. However, all of these require special privileges in order to run. Alas, since I'm running on a page with frames, because of a known defect in Chrome, I can't access the frames. So I can load a script into each frame by using all_frames: true, but I really want to avoid loading the script with every frame load. Otherwise, according to this article, I need to escape the sandbox, but then it comes back to privileges.
Since you are running on Chrome and Firefox, your answer is fortunately, yes (kind of). function base64img(i){ var canvas = document.createElement('canvas'); canvas.width = i.width; canvas.height = i.height; var context = canvas.getContext("2d"); context.drawImage(i, 0, 0); var blob = canvas.toDataURL("image/png"); return blob.replace(/^data:image\/(png|jpg);base64,/, ""); } this will return the base64 encoded image. from there you just call the function something along these lines: image = document.getElementById('foo') imgBlob = base64img(image); Then go ahead and store imgBlob. Edit: As file size is a concern, you can also store the data as a canvasPixelArray, which is width*height*4 bytes in size. imageArray = context.getImageData( 0, 0 ,context.canvas.width,canvasContext.canvas.height ); Then JSONify the array and save that?
Programmatically check and update only if an image has changed
I have an application which updates an image from time to time. The update interval is not predictable. The image itself is updated atomically on the web server via rename(). That is all this application does and there shall be no change on the Apache side such that the webserver can continue to only serve static files. There is some AJAX script which displays the content and updates this image when it is changed. This is done using polling. The naive JavaScript version used a counter and updated pulled the image each second or so by adding a query timestamp. However 99% of the time this pulls the image unchanged. The current not so naive version uses XMLHttpRequest aka. AJAX to check the If-Modified-Since-header, and if a change is detected the update is invoked. The question now is, is there a better way to archive this effect? Perhaps look at the last paragraph of this text before you dive into this ;) Here are the core code snippets of the current version. Please note that the code is edited for brevity, so var initialization left away and some lines removed which are not of interest. First the usual, slightly extended AJAX binding: // partly stolen at http://snippets.dzone.com/posts/show/2025 function $(e){if(typeof e=='string')e=document.getElementById(e);return e}; ajax={}; ajax.collect=function(a,f){var n=[];for(var i=0;i<a.length;i++){var v=f(a[i]);if(v!=null)n.push(v)}return n}; ajax.x=function(){try{return new XMLHttpRequest()}catch(e){try{return new ActiveXObject('Msxml2.XMLHTTP')}catch(e){return new ActiveXObject('Microsoft.XMLHTTP')}}}; ajax.send=function(u,f,m,a,h){var x=ajax.x();x.open(m,u,true);x.onreadystatechange=function(){if(x.readyState==4)f(x.responseText,x,x.status==0?200:x.status,x.getResponseHeader("Last-Modified"))};if(m=='POST')x.setRequestHeader('Content-type','application/x-www-form-urlencoded');if(h)h(x);x.send(a)}; ajax.get=function(url,func){ajax.send(url,func,'GET')}; ajax.update=function(u,f,lm){ajax.send(u,f,'GET',null,lm?function(x){x.setRequestHeader("If-Modified-Since",lm)}:lm)}; ajax.head=function(u,f,lm){ajax.send(u,f,'HEAD',null,lm?function(x){x.setRequestHeader("If-Modified-Since",lm)}:lm)}; The basic HTML part, it includes 2 images which are flipped after loading, and a third one (not referenced in the code snippets) to display archived versions etc., which prevents flipping the updates as well: </head><body onload="init()"> <div id="shower"><img id="show0"/><img id="show1"/><img id="show2"/></div> The initial part includes the timer. It is a bit more to it, to compensate for network delays on slow links, reduce the polling rate etc.: function init() { window.setInterval(timer,500); for (var a=2; --a>=0; ) { var o=$("show"+a); o.onload = loadi; } disp(0); } function disp(n) { shown=n; window.setTimeout(disp2,10); } function disp2() { hide("show0"); hide("show1"); hide("show2"); show("show"+shown); } function hide(s) { $(s).style.display="none"; } function show(s) { $(s).style.display="inline"; } function timer(e) { if (waiti && !--waiti) dorefresh(); nextrefresh(); } function nextrefresh() { if (sleeps<0) sleeps = sleeper; if (!--sleeps) pendi = true; if (pendi && !waiti) dorefresh(); } From time to time dorefresh() is called to pull the HEAD, tracking If-Modified-Since: function dorefresh() { waiti = 100; // allow 50s for this request to take ajax.head("test.jpg",checkrefresh,lm); } function checkrefresh(e,x,s,l) { if(!l) { // not modified lmc++; waiti = 0; } else { lmc=0; lm=l; $("show"+loadn).src = "test.jpg?"+stamp(); waiti=100; } pendi=false; sleeper++; if (sleeper>maxsleep) sleeper = maxsleep; sleeps=0; nextrefresh(); } function stamp() { return new Date().getTime(); } When the image is loaded it is flipped into view. shown usually is 0 or 1: function loadi() { waiti=0; $("show"+loadn).style.opacity=1; if (shown<2) disp(loadn); loadn=1-loadn; } Please note that I only tested this code with Webkit based browsers yet. Sorry, I cannot provide a working example, as my update source is non-public. Also please excuse that the code is somewhat quick-n-dirty quality. Strictly speaking HEAD alone is enough, we could look at the Last-Modified header of course. But this recipe here also works for GET requests in a non-image situation. AJAX GET in combination with images makes less sense, as this pulls the image as binary data. I could convert that into some inline image, of course, but on bigger images (like mine) this will exceed the maximum URL length. One thing which possibly can be done is using the browser cache. That is pull the image using an ajax.update and then re-display the image from the cache. However this depends on the cache strategy of a browser. On mobile devices the image might be too big to be cached, in that case it is transferred twice. This is wrong as usually mobile devices have slow and more important expensive data links. We could use this method if the webserver would write a text file, like JSON or a JS snippet, which then is used to display the image. However the nice thing about this code here is, that you do not need to provide additional information. So no race conditions, no new weird states like in disk full cases, just works. So one basic idea is to not alter the code on the webserver which generates the picture, just do it on the browser side. This way all you need is a softlink from the web tree to the image and make sure, the image is atomically updated. The downside of AJAX is the same origin policy, so AJAX can only check the HEAD of resources from the host which provided the running JavaScript code. Greasemonkey or Scriptlets can circumvent that, but these cannot be deployed to a broad audience. So foreign resources (images) sadly cannot be efficiently queried if they were updated or not. At my side luclily both, the script and the image, originate from the same host. Having said this all, here are the problems with this code: The code above adds to the delay. First the HEAD is checked and if this shows that something has changed the update is done. It would be nice to do both in one request, such that the update of the image does not require an additional roundtrip. GET can archive that with If-Modified-Since, and it works on my side, however I found no way to properly display the result as an inlined image. It might work for some browsers, but not for all. The code also is way too complex for my taste. You have to deal with possible network timeouts, not overwhelming limited bandwidth, trying to be friendly to the webserver, being compatible to as many browsers as possible, and so on. Also I would like to get rid of the hack to use a query parameter just to pull an updated image, as this slowly fills/flushes the cache. Perhaps there is an - unknown to me - way to "re-trigger" image refresh in the browser? This way the browser could check with If-Modified-Since directly and update the image. With JavaScript this could trigger a .load event then or similar. At my side I even do not need that at all, all I want is to keep the image somewhat current. I did not experiment with CANVAS yet. Perhaps somebody has an idea using that. So my question just is, is there any better way (another algorithm) than shown above, except from improving code quality?
From what I understand, you have 2 sources of information on the server: the image itself and time of last update. Your solution polls on both channels and you want to push, right? Start here: http://en.wikipedia.org/wiki/Comet_(programming), there should be a simple way to let the server update the client on a new image url. In case server and client support websockets it's a shortcut. However, most simple solution assumes no image url change and runs image.src = ""; image.src = url; by using setInterval() and let the browser deal with cache and headers.