How do I refresh a remote picture? - javascript

I have a picture in a DIV on site abc.com which is hosted elsewhere, for example <IMG SRC="http://xyz.com/image.jpg">.
It loads fine, but, I need to update this every few seconds.
The majority of items to upload are local, but the following code will not work for remote pictures:
$('#rightpic').load('http://xyz.com/image.jpg', null);
By trying this, I am getting an error : ...is not allowed by Access-Control-Allow-Origin.
Can anyone recommend a better way of doing this?

Try this out, you want to actually change the src, not use the .load() function.
$('#rightpic').get(0).src = 'http://xyz.com/image.jpg';

.load uses an AJAX request, thus the same origin policy applies - which restricts cross-domain requests. Besides, it's not the best way to load images anyway. Also, setting the same url as src will often load images from the cache.
Instead, you should add a random query string value every request, like a timestamp, to "bust the cache"
var img = document.getElementById('rightpic');
//update every 10 seconds using time from epoch as random value
setInterval(function(){
var randomValue = new Date().getTime();
img.src = "http://example.com/image.jpg?t="+randomvalue;
},10000);

Related

Auto refresh specific div and load image with jquery/ajax

I have an internet radio station and I need a script that will display a picture of the current song in a particular dvi with an id. The image is automatically uploaded via ftp to the server each time the song changes..
HTML:
<div id="auto"></div>
JS:
$ (document).ready(function() {
$('#auto').html('<img src="artwork.png"></img>');
refresh();
});
function refresh() {
setTimeout (function() {
$('#auto').html('<img src="artwork.png"></img>');
refresh();
}, 1000);
}
I tried this, but all I get is that the image is loaded, but in case of a change, I have to manually refresh the whole page again..
I'll point out multiple things here.
I think your code is just fine if you are going for the setTimeout recursive calls instead of one setInterval action to repeat it.
File Caching
your problem is probably the browser's cache since you are using the same image name and directory all the time. browsers compare the file name and directory and to decide to load it from its cache or else it will request it from the server. there are different tricks you can do to reload the image from the server in this particular case.
Use different file names/directories for the songs loaded dynamically
Use a randomized GET query (e.g. image.png?v=current timestamp)
Your method for switching
you are replacing the file with FTP, I wouldn't recommend that. maybe you should have all your albums and thumbnails uploaded to the server and use a different dynamic switching for efficiency and less error proneness and will help you achieve method #1 in the previous section better.
Loading with constant refresh
I would like to highlight that if you are using nodeJs or nginx servers - which are event based - you can achieve the same functionality with much less traffic. you don't need a refresh method since those servers can actually send data on specific events to the browser telling it to load a specific resource at that time. no constant refresh is required for this.
You consider your options, I tried to be as comprehensive as I could
At the top level, browser cache the image based on its absolute URL. You may add extra query to the url to trick browser that is another new image. In this case, new URL of artist.png will be artist.png?timestamp=123
Check this out for the refresh():
function refresh() {
setTimeout (function() {
var timestamp = new Date().getTime();
// reassign the url to be like artwork.png?timestamp=456784512 based on timestmap
$('#auto').html('<img src="artwork.png?timestamp='+ timestamp +'"></img>');
refresh();
}, 1000);
}
You may assign id attribute to the image and change its src url
html
<img id="myArtworkId" src="artwork.png"/>
js in the refresh method
$('#myArtworkId').attr('src', 'artwork.png?timestamp=' + new Date().getTime());
You can use window.setInterval() to call a method every x seconds and clearInterval() to stop calling that method. View this answer for more information on this.
// Array containing src for demo
$srcs = ['https://www.petmd.com/sites/default/files/Acute-Dog-Diarrhea-47066074.jpg',
'https://www.catster.com/wp-content/uploads/2018/05/Sad-cat-black-and-white-looking-out-the-window.jpg',
'https://img.buzzfeed.com/buzzfeed-static/static/2017-05/17/13/asset/buzzfeed-prod-fastlane-03/sub-buzz-25320-1495040572-8.jpg?downsize=700:*&output-format=auto&output-quality=auto'
]
$i = 0;
$(document).ready(function() {
$('#auto').html('<img src="https://images.pexels.com/photos/617278/pexels-photo-617278.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"></img>');
// call method after every 2 seconds
window.setInterval(function() {
refresh();
}, 2000);
// To stop the calling of refresh method uncomment the line below
//clearInterval()
});
function refresh() {
$('#auto').html('<img src="' + $srcs[$i++] + '"></img>');
// Handling of index out of bound exception
if ($srcs.length == $i) {
$i = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="auto"></div>

JavaScript - Measure remote pages' load times

I'd like to have a very simple page on my server, which uses JS to measure the time it takes to load the login web page on several remote URLs/servers. These servers are located around the world, and I'd like to measure the times in order to choose the fastest one for my location (i.e. the code will run client-side of course, on the user's browser).
Example:
server1.example.com: 200 ms
server2.example.com: 400 ms
server3.example.com: 2 ms
There's a lot of software that does this general idea (from simple pinging to wget, etc.), but I'm looking for JS code that I can use in a simple page which will try these requests and display the times.
The basic way I tried until now (simple Ajax requests using jQuery) doesn't work because of CORS errors. Any ideas for the simplest solution would be awesome.
You can load images without any restrictions, so take advantage of them:
function ping(url) {
var img = new Image(),
start = Date.now();
img.onload = function () {
console.log(url, 'loaded in', Date.now() - start, 'ms');
};
img.src = url + '?' + Math.random();
document.body.appendChild(img);
}
ping('https://facebook.com/favicon.ico');
ping('https://www.bing.com/favicon.ico');
ping('https://youtube.com/favicon.ico');
By the way, for accurate results, make sure the images are the same size.

How to force a hard refresh after jQuery submit (Internet Explorer)

I'm trying to upload a picture to a server. Once the upload is finished, the page automatically refreshes. All is well in FF, Chrome etc, but in IE the new page is not updated with the new photo. This behaviour is by design: http://support.microsoft.com/kb/237885
Is there a way to force a hard refresh after a jQuery.submit?
You can set your webserver to emit no-cache headers for that particular image; but that will effect every client on every request, and so is not ideal.
The best solution would be to change the URL of the resource; either in JavaScript or on the server. Adding a query string to the URL will be enough to force a refresh... e.g change:
/my_image.jpg
to
/my_image.jpg?version=2
To generate a number, you could use the timestamp ((new Date()).getTimestamp() in JavaScript), or a random number (Math.random() * 1000000).
A complete JavaScript solution would be to add a class to the image you want to refresh (e.g. force-reload), and to put the src as a data- property instead;
<img class="force-reload" data-src="/my_image.jpg"/>
Then in jQuery:
$(document).ready(function () {
var now = (new Date()).getTime();
$('img.force-reload').prop('src', function () {
return $(this).data('src') + "?" + now;
});
});
Add a query string with timestamp to an image url, like so:
<img src="/path/to/image.jpg?1234567890"/>
This will force to clear the all browsers cache.

image polling through javascript

I need to poll an image using javascript and need to perform an action once the image is found at its position. This is the code I have written for this task.
/*----Image handling script starts here----*/
var beacon = new Image();
beacon.onload = function() {
console.log('Image found');
console.log(this.width,this.height);
window.clearInterval(timer);
};
beacon.onerror = function(){
console.log('Image not found');
}
var timer = window.setInterval(function(){
console.log('sending the request again');
beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif";
},2000);
/*----Image handling script ends here----*/
Problem is that, after one GET request, the response gets cached and request don't get sent everytime I set src. If you examine NET tab, it sends request only on first src set and caches the response.
I need to send a fresh request for image every time my code sets the src. Any workarounds?
Change your src to include the current EPOCH time as a variable.
beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif?" +
date.getTime();
Using a different variable in the query string each time will miss out caching, because as far as the browser is concerned, the image is different (or potentially could be) each time you request the image, and there is no limit to the amount of times you ask, as time hopefully will not stop...
Request the image with a different query string each time. The browser will treat it as a unique URL and won't have it in the cache. You can probably get away with this because it's likely the web server will ignore anything in the query string when requesting an image. The following should make 100 requests:
for (var i=0; i<100; i++)
{
beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif?" + i;
}

Any way to gracefully enforce a timeout limit when loading a slow external file via javascript?

I'm using javascript to include some content served up from a php file on another server. However, this other service can sometimes get flaky and either take a long time to load or will not load at all.
Is there a way in JS to try to get the external data for x number of seconds before failing and displaying a "please try again" message?
<script type="text/javascript" src="htp://otherserver.com/myscript.php"></script>
Couple issues: you can use timeout thresholds with XMLHttpRequest (aka ajax), but then since it's on an otherserver.com you cannot use XMLHttpRequest (and support all A-grade browsers) due to the Same Origin Policy restriction.
If the script introduces any kind of global name (eg any variable name, function name, etc) You can try setTimeout to keep checking for it:
var TIMELIMIT = 5; // seconds until timeout
var start = new Date;
setTimeout(function() {
// check for something introduced by your external script.
// A variable, namespace or function name here is adequate:
var scriptIncluded = 'otherServerVariable' in window;
if(!scriptIncluded) {
if ((new Date - start) / 1000 >= TIMELIMIT) {
// timed out
alert("Please try again")
}
else {
// keep waiting...
setTimeout(arguments.callee, 100)
}
}
}, 100)
The problem as I see it is you cannot cancel the request for the script. Please someone correct me if I'm wrong but removing the <script> from the DOM will still leave the browser's request for the resource active. So although you can detect that the script is taking longer than x seconds to load, you can't cancel the request.
I think you may be out of luck.
The only way I can think of doing this is to create a proxy on another (PHP-enabled) server which will fetch the data for you, but will stop when a certain timeout limit has been reached (and it can just return an empty result).
This is purely, purely theoretical:
<script> tags can be dynamically inserted into the DOM, at which point the script will be fetched and processed. This dynamic script tag injection is how some achieve cross-domain "AJAX."
I would imagine you could declare a global variable var hasLoaded = false;. At the end of the script you are attempting to load you could set that variable to true hadLoaded=true;. After injecting the script tag into the DOM you could then kickoff a setTimeout() whose callback function checks to see if "hasLoaded" is set to true. If it isn't, you can assume the script has not yet loaded fully into the browser. If it has, you can assume it has loaded completely.
Again, this is theoretical, but if you test it be sure to report back, I'm very curious.
I think that the only way to do this is take the content of the file via ajax and then set a timer. If the request finishes before the timer you can evaluate the respons with eval(that's not the better solution anyway), otherwise you can stop the ajax request and write the error message.

Categories

Resources