images not loading in websockets - websocket

I have a problem loading images
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
alert('it loaded');
bgReady = true;
};
bgImage.src = "images/background.png";
the alert does not appear when the websocket server is running.
The alert will appear if I remove the socket code and turn the server off.
I have already placed alerts throughout the code to see how far it will run without breaking.
Nothing seems to be breaking except the image does not seem to want to load.
any suggestions will be helpful.

I was accessing files from a different port so thats why they were not loading

Related

StaticImage in a layer. Is the change of source synchronous or asynchronous?

I'm developing a an application which displays images ( png ) in a layer of an OpenLayer's map. So far so good, it works like a charm. Nonetheless it may happen
that the requested image has to be created on the fly by the server and then a delay of few or more seconds can be observed before the image appears on the client's side. To make the user understand that displaying the image takes some time I use an animation that appears when the request is sent to the server and should disappear when the image is served and displayed (see code below). What I observe though is that the animation never appears exactly as is the service of the image was processed in an asynchronous way. I really would like to know if my interpretation is correct and in such a case which can of event I should trap and only then make the animation disappear.
document.getElementById('loading').style.display='block';
_im_layer_1 = new ol.layer.Image({
source: new ol.source.ImageStatic({
url: 'http://'+server+':'+port+'/png/?path="'+_path+'"&si='+_sliceIndex,
projection: _projection_1,
imageExtent: _extent
})
});
console.log("adding the image layer");
_map_1.addLayer(_im_layer_1);
document.getElementById('loading').style.display='none';
I was expecting to listen to the source with
imageStaticSource.on('change', evt => {
console.log('no event, contrary to what I would expect');
});
but it fails contrary to what I expected from the API docs.
So, looking at the code, I've seen there is an imageLoadFunction option for the ol.source.ImageStatic constructor. When not set, this function fallback to a default one. I've created a new one, derived from the default and made some changes to demonstrate how you can get the start of the loading event and then the end of it.
You will find a demo derived from the official sample that should illustrate the process. Try it on you side as the demo does not wait some seconds to return the image, contrary to your use case.
var imageLoadFunction = function(image, src) {
// Where you start showing the loader using a variable
console.time('loader');
image.getImage().addEventListener('load', function() {
// Where you should mention to stop the loader
console.timeEnd('loader');
});
image.getImage().src = src;
};
var imageStaticSource = new ol.source.ImageStatic({
attributions: '© xkcd',
url: 'https://imgs.xkcd.com/comics/online_communities.png',
projection: projection,
imageLoadFunction: imageLoadFunction,
imageExtent: extent
});

Chrome: Prevent image reload when rebuilding image elements

Using AngularJS:
I'm displaying a list of images with ng-repeat. When I reset and rebuild the model (get new data from backend), I'm displaying the same images as before.
I understand these are new elements created by ng-repeat, but the image srcs are the same. Unlike IE or firefox, Chrome tries and gets a 403 for those same images and then renders them.
That causes a flicker. On IE and Firefox the images come from cache. No hit on the server to check for image changes. No flicker.
How can I prevent that? Should the images be served with some cache header? I tried loading the images to a dataurl, but then I hit the CORS problem, and would have to proxy those images on the backend to get them.
Possibly related: Chrome sometimes reloads image after jQuery .appendTo, recieves 304
Thanks
Some fix would be related to preload the images in javascript and after that display them
function loadImages(arrayOfImgs) {
var imageNumber=0;
$(arrayOfImgs).each(function(){
(new Image()).src = this;
if(arrayOfImgs.length == imageNumber) $scope.showImages = true;
else imageNumber++;
});
}
// Usage:
loadImages([
'img1.jpg',
'img2.jpg'
]);
if you are retriving images from backend use it at success promise
i hope it helps you
Check that example retrinving images from backend:
$scope.loading = true;
getImages().then(function (response) {
var objects= response.results;
var listImages = [];
angular.forEach(objects, function (item) {
listImages.push(item.UrlImage);
});
function preload(arrayOfImages) {
var numImages = 0;
$(arrayOfImages).each(function () {
var img = (new Image());
img.src = this;
$(img).load(function () {
numImages++;
if (numImages == arrayOfImages.length){
$scope.loading = false;
}
});
});
}
preload(listImages);
});

How can I dynamically change kendo.mobile.Application's loading property?

I am developing a mobile web app using Kendo UI Mobile. Whenever we make any AJAX calls, or our DataSources make them we call app.startLoading() to show the loading icon to the user. This works very well.
However, depending on the context in which the call is made we would like to change the text that is displayed along with the loading icon. I know you can define this when I create the kendo.mobile.Application instance. How can I change it afterwards?
The documentation does not suggest a way to do this, and a browse of the source code did not help me either. Is this really not possible?
EDIT: This is using Kendo UI Mobile v.2012.3.1114
I usually make a "utility" function to do this:
var _kendoApp = new kendo.mobile.Application(document.body, {});
var showLoading = function (message) {
_kendoApp.loading = "<h1>" + (message ? message : "Loading...") + "</h1>";
_kendoApp.showLoading();
};
I am also setting a default message of "Loading..." if one isn't passed in.
Edit:
I could have sworn that worked for me in a past app I did, but judging by thr source, I think you are right, my answer above shouldn't work. My best suggestion is to add a class to the message element so you can target it, and use jQuery to change the text.
var _kendoApp;
var showLoading = function (message) {
$(".loading-message").text(message ? message : "Loading...");
_kendoApp.showLoading();
};
_kendoApp = new kendo.mobile.Application(document.body, {
loading: '<h1 class="loading-message">Loading...</h1>'
});

jQuery .load() wait till content is loaded

How to prevent jQuery $('body').load('something.php'); from changing any DOM till all the content from something.php (including images,js) is fully loaded
-Lets say some actual content is:
Hello world
And something.php content is:
image that loads for 10 seconds
20 js plugins
After firing .load() function nothing should happen, till images an js files are fully loaded, and THEN instantly change the content.
some preloader may appear, but its not subject of question.
[edit]----------------------------------------------------------------------
My solution for that was css code (css is loaded always before dom is build) that has cross-browser opacity 0.
.transparent{
-moz-opacity: 0.00;
opacity: 0.00;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha"(Opacity=0);
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0);
filter:alpha(opacity=0);
}
And it prevent from bad flickr of content usually but not always. Now its possible to detect somehow that content is loaded by jQuery ajax and apply some show timeout and so on. But in fact question is still open.
To make now a little more simple example for that question:
How to begin changing DOM after $('body').load('something.php') with 3000ms delay after clicking the link that fire .load('something.php') function? (Browser should start downloading instantly, but DOM changing has to be initiated later)
Use .get instead and assign the contents in the success callback:
$.get('something.php', function(result) {
$('body').html(result);
});
There are some implementation details you may have to solve yourself, but here's a rough solution:
Don't use .load() directly. It can't be changed to wait for all images to load.
Use $.get() to fetch the HTML into a variable, let's call it frag.
Use $(frag).find('img').each(fn) to find all images and dump each this.src inside a preloader.
var images = [],
$frag = $(frag),
loaded = 0;
function imageLoaded()
{
++loaded;
// reference images array here to keep it alive
if (images.ready && loaded >= images.length) {
// add $frag to the DOM
$frag.appendTo('#container');
}
}
$frag.find('img').each(function() {
var i = new Image();
i.onload = i.onerror = imageLoaded;
i.src = this.src;
images[images.length] = i;
});
// signal that images contains all image objects that we wish to monitor
images.ready = true;
Demo
Once all images are loaded, append the earlier frag to the DOM using $frag.appendTo('#container').
Here is a quick proof of concept that loads relevant images before inserting an HTML fragment into the DOM: http://jsfiddle.net/B8B6u/5/
You can preload the images using the onload handler to trigger iterations:
var images = $(frag).find('img'),
loader = $('<img/>');
function iterate(i, callback) {
if (i > 0) {
i--;
loader.unbind("load");
loader.load(function() {
iterate(i, callback);
});
loader.attr('src', images[i].src);
}else{
callback();
}
}
iterate(images.length,function(){
$('#container').html(frag);
});
This should work, since each image is loaded after the previous one has finished loading.
Have you tried this?
$(function(){$('body').load('something.php')});
Edit: I just realized you are actually wanting to wait for the stuff to load before it get's placed in the body.
Here are three links to similar questions.
Preloading images with jQuery
Is it possible to preload page contents with ajax/jquery technique?
Preloading images using PHP and jQuery - Comma seperated array?
You can probably adapt those to scripts too.
This might work too.
$.ajax({
'url': 'content.php',
'dataType': 'text',
'success': function(data){
var docfrag = document.createDocumentFragment();
var tmp = document.createElement('div'), child;
//get str from data here like: str data.str
tmp.innerHTML = str;
while(child = tmp.firstChild){
docfrag.appendChild(child);
}
$('body').append(docfrag);
}
});
It's a longer way of doing what Shadow Wizard suggests, but it will probably work.
Hm. Never mind. Jack's answer looks the best. I'll wait a while and if no one likes my answer I'll delete it.
Edit: It looks like appending to documentfragments can do http requests.
Any script using createDocumentFrament may benefit from preloading.
In this question they want no http requests even though that's what createDocumentFragment is doing:
Using documentFragment to parse HTML without sending HTTP requests.
I can't be sure if this is true for all browsers or just when the console.log is run, but it could be a good option for preloading if this behavior is universal.

Help me understand how google maps show images?

With firebugs net tab open i stated zooming in and out of google map and i found its making requests for the png images.
Ok with this i understood that we can request the images using the Ajax. but wait ? i always used to request html, jsox, txt and xml. Image ........ its strange for me ? Can some one please elaborate on this ?
Also i would like to know if text is downloaded we add it to some DOM element and it show up. How images retried from the ajax can be accessed ?
Any help or pointer will be great help :)
GMaps doesn't make XMLHttpRequests to get the images. They instead use a normal <img /> element that is injected via javascript.
They then use the "onload" and "onerror" events to detect if the image was loaded correctly.
They retry a download of the image if it times out. This is achieved by setting a timer and once it expires re-setting the src property of the image.
var tile = document.createElement('img');
var url = 'http://sometilehost/X.Y.Z.png';
var downloadTimeout = 10000; // Retry in 10 seconds
// Tile downloaded successfully
tile.onload = function (e) {
window.clearTimeout(tile.downloadTimer);
alert('tile downloaded');
};
// The tile couldn't be downloaded. 404, 503 ...
tile.onerror = function (e) {
window.clearTimeout(tile.downloadTimer);
alert('tile not downloaded');
};
// This will fire if the tile doesn't download in time
tile.downloadTimer = window.setTimeout(function () {
tile.src = url; // Start the download again
}, downloadTimeout);
tile.src = url;

Resources