stop iframe flickering when it refreshes - javascript

i have an iframe that loads my chatbox, but when it refreshed it flickers, how would I go about stopping it flickering. I have included the code below that I use to refresh the Iframe its self.
window.setInterval("reloadIFrame();", 2000);
function reloadIFrame() {
window.frames["chatlogs"].location.reload();
}
Thanks in advance for any help!

Not only might you want to use AJAX instead of an iframe, but depending on requirements you might also want to go look into using a server-side push. The problem being solved is, how does a client update its content when an event occurs on the server? Chat is a classic example of this. You have several options available to you, which I list below.
Frequent polling
The simplest solution. Each client repeatedly asks the server if there are any updates and is the closest to your iframe implementation. The downside comes from wasted bandwidth from communication overhead of each client request.
Long polling / Comet
when where the server keeps the clients waiting for a longer time (i.e. 5 sec) before returning as soon as an update occurs or timeout, whichever is sooner. With Comet, the server needs to be coded to keep client connections open without keeping any server threads waiting (otherwise the server will run out of threads to serve new requests and it'll be a performance nightmare).
WebSockets
New in HTML 5, WebSockets support bidirectional communication between client and server and are the recommended technology for any communication for server-side push.
You can find a good example with WebSockets here, which, guess what? Happens to be a guy trying to implement a chat application :)
Misc
For the record, you'll be able to eliminate iframe flicker if instead of keeping one iframe and refreshing it, your JavaScript creates a new hidden iframe with the same URL and position as the old one, and when it loads make it visible and delete the old iframe.

Related

javascript setInterval() load

I am trying to figure out what kind of load the window function setInterval() places on a user's computer. I would like to place a setInterval() on a page that is viewable only by my company's employees that will be checking a basic text file every 5 seconds or so and then if there is something to display, it will throw up some html code dynamically on the screen.
Any thoughts? Any better, less intrusive way to do this?
Appears it should not cause a problem, pending that the function setInterval() fires off is not heavy. Since I will only be reading a text file which should never be too large (text file will be overwritten about every minute by a completely separate job or bash script), the load should be minimal since it will be read in as a string, analyzed, and if necessary throw out a small amount of HTML code to the page.
I agree with all the comments regarding a single, polling setInterval() to be trivial.
However, if you want alternatives:
Long Polling
The browser makes an Ajax-style request to the server, which is kept
open until the server has new data to send to the browser, which is
sent to the browser in a complete response.
Also see:
PHP example and explanation
SignalR
Web Sockets
WebSockets is an advanced technology that makes it possible to open an
interactive communication session between the user's browser and a
server. With this API, you can send messages to a server and receive
event-driven responses without having to poll the server for a reply.

Prevent recursive calls of XmlHttpRequest to server

I've been googling for hours for this issue, but did not find any solution.
I am currently working on this app, built on Meteor.
Now the scenario is, after the website is opened and all the assets have been loaded in browser, the browser constantly makes recursive xhr calls to server. These calls are made at the regular interval of 25 seconds.
This can be seen in the Network tab of browser console. See the Pending request of the last row in image.
I can't figure out from where it originates, and why it is invoked automatically even when the user is idle.
Now the question is, How can I disable these automatic requests? I want to invoke the requests manually, i.e. when the menu item is selected, etc.
Any help will be appriciated.
[UPDATE]
In response to the Jan Dvorak's comment:
When I type "e" in the search box, the the list of events which has name starting with letter "e" will be displayed.
The request goes with all valid parameters and the Payload like this:
["{\"msg\":\"sub\",\"id\":\"8ef5e419-c422-429a-907e-38b6e669a493\",\"name\":\"event_Coll_Search_by_PromoterName\",\"params\":[\"e\"]}"]
And this is the response, which is valid.
a["{\"msg\":\"data\",\"subs\":[\"8ef5e419-c422-429a-907e-38b6e669a493\"]}"]
The code for this action is posted here
But in the case of automatic recursive requests, the request goes without the payload and the response is just a letter "h", which is strange. Isn't it? How can I get rid of this.?
Meteor has a feature called
Live page updates.
Just write your templates. They automatically update when data in the database changes. No more boilerplate redraw code to write. Supports any templating language.
To support this feature, Meteor needs to do some server-client communication behind the scenes.
Traditionally, HTTP was created to fetch dead data. The client tells the server it needs something, and it gets something. There is no way for the server to tell the client it needs something. Later, it became needed to push some data to the client. Several alternatives came to existence:
polling:
The client makes periodic requests to the server. The server responds with new data or says "no data" immediately. It's easy to implement and doesn't use much resources. However, it's not exactly live. It can be used for a news ticker but it's not exactly good for a chat application.
If you increase the polling frequency, you improve the update rate, but the resource usage grows with the polling frequency, not with the data transfer rate. HTTP requests are not exactly cheap. One request per second from multiple clients at the same time could really hurt the server.
hanging requests:
The client makes a request to the server. If the server has data, it sends them. If the server doesn't have data, it doesn't respond until it does. The changes are picked up immediately, no data is transferred when it doesn't need to be. It does have a few drawbacks, though:
If a web proxy sees that the server is silent, it eventually cuts off the connection. This means that even if there is no data to send, the server needs to send a keep-alive response anyways to make the proxies (and the web browser) happy.
Hanging requests don't use up (much) bandwidth, but they do take up memory. Nowadays' servers can handle multiple concurrent TCP connections, so it's less of an issue than it was before. What does need to be considered is the amount of memory associated with the threads holding on to these requests - especially when the connections are tied to specific threads serving them.
Browsers have hard limits on the number of concurrent requests per domain and in total. Again, this is less of a concern now than it was before. Thus, it seems like a good idea to have one hanging request per session only.
Managing hanging requests feels kinda manual as you have to make a new request after each response. A TCP handshake takes some time as well, but we can live with a 300ms (at worst) refractory period.
Chunked response:
The client creates a hidden iFrame with a source corresponding to the data stream. The server responds with an HTTP response header immediately and leaves the connection open. To send a message, the server wraps it in a pair of <script></script> tags that the browser executes when it receives the closing tag. The upside is that there's no connection reopening but there is more overhead with each message. Moreover, this requires a callback in the global scope that the response calls.
Also, this cannot be used with cross-domain requests as cross-domain iFrame communication presents its own set of problems. The need to trust the server is also a challenge here.
Web Sockets:
These start as a normal HTTP connection but they don't actually follow the HTTP protocol later on. From the programming point of view, things are as simple as they can be. The API is a classic open/callback style on the client side and the server just pushes messages into an open socket. No need to reopen anything after each message.
There still needs to be an open connection, but it's not really an issue here with the browser limits out of the way. The browser knows the connection is going to be open for a while, so it doesn't need to apply the same limits as to normal requests.
These seem like the ideal solution, but there is one major issue: IE<10 doesn't know them. As long as IE8 is alive, web sockets cannot be relied upon. Also, the native Android browser and Opera mini are out as well (ref.).
Still, web sockets seem to be the way to go once IE8 (and IE9) finally dies.
What you see are hanging requests with the timeout of 25 seconds that are used to implement the live update feature. As I already said, the keep-alive message ("h") is used so that the browser doesn't think it's not going to get a response. "h" simply means "nothing happens".
Chrome supports web sockets, so Meteor could have used them with a fallback to long requests, but, frankly, hanging requests are not at all bad once you've got them implemented (sure, the browser connection limit still applies).

change content in all users pages when at least 1 user triggers event without page refresh

What I want to do is when 1 user checks a checkbox(just for example, it can be any event), everyone, who have same page opened, immediately saw it without page refresh.
I know how to do it with ajax and setTimeOut(or setInterval) function: with setTimeOut function we open stream where an infinite loop checks if an event was triggered and if yes, we update content with ajax. Or set interval to update page in some time.
I'm looking for more optimized and cross-browser solution, so any help will be appreciate.
Search google for: Comet or long polling
For the solution to be cross-browser, you have to bend what web-servers/HTTP were designed for, which is for requests from browsers being served a page as quickly as possible, and then closing the connection. There are new methods with new browsers, and new definitions in the HTTP model, but they will not work on old browsers.
The basic principle behind long polling, is that a request is sent to the server, which idles around, pretending to be generating the page, and if any event happens requiring the client to be updated, it then sends the information as the response to the request which pre-dated the request. This is inefficient in terms of server resources, but about as snappy as you can get in terms of user experience.

Best practice use sam AJAX in multiple browser windows?

I am developing a website that has some sort of realtime update.
Now the website is generated with a javascript variable of the current ID of the dataset.
Then in an interval of some seconsd an AJAX call is made passing on the current ID, and if theres something new the server returns it along with the latest ID which is then updated in the javascript.
Very simple, but here comes the Problem.
If the user opens the same page multiple times, every page does this AJAX requests which produces heavy serverload.
Now I thought about the following approach:
The website is loaded with a javascript variable of the current timestamp and ID of the current dataset.
My desired refresh interval is for example 3 seconds.
In the website an interval counter counts up every seconds, and everytime the timestamp reaches a state where (timestmap % 3===0) returns true, the content is updated.
The link looks like http://www.example.com/refresh.php?my-revision=123&timestamp=123456
Now this should ensure that every browser window calls the same URL.
Then I can turn on browser level caching.
But I don't really like this solution.
I would prefer adding another layer of data sharing in a Cookie.
This shouldn't be much of a problem, I can just store every request in a cookie named by timestamp and data revision with a TTL of 10 seconds or so and check for its exitence first.
BUT
The pages will do the request at the same time. So the whole logic of browser caching and cookie might not work because the requests occour simultanously and not one after another.
So I thought about limiting the current connections to 1 server side. But then I would need at least an extra vhost, because I really dont want to do that for the whole page.
And this lets me run into problems concerning cross-site policies!
Of course there are some super complicated load balancing solutions / server side solusions bound to request uri and ip adress or something but thats all extreme overkill!
It must be a common problem! Just think of facebook chat. I really don't think they do all the requests in every window you have open...
Any ideas? I'm really stuck with this one!
Maby I can do some inter-window Javascript communication? Shouldnt be a problem if its all on the same domain?
A thing I can do of course is server side caching. Which avoids at least DB Connections and intensive calculations... but it still is an request which I would like to avoid.
You might want to check out Comet and Orbited .
This is best solved with server push technology.
The first thing is: Do server-side caching anyway, using Memcache or Redis or whatever. So you're defended against three machines doing the requests. But you knew that.
I think you're onto the right thing with cookies, frankly (but see below for a more modern option) — they are shared by all window instances, easily queried, etc. Your polling logic could look something like this:
On polling interval:
Look at content cookie: Is it fresher than what you have? If so, use it and you're done.
Look at status cookie; is someone else actively polling (e.g., cookie is set and not stale)? If yes, come back in a second.
Set status cookie: I'm actively polling at (now).
Do request
On response:
If the new data is newer than the (possibly updated) contents of the content cookie, set the content cookie to the new data
Clear status cookie if you're the one who set it
Basically, the status cookie acts as a semaphore indicating to all window instances that someone, somewhere is on the job of updating the content.
Your content cookie might contain the content directly, or if your content is large-ish and you're worried about running into limits, you could have each page have a hidden iframe, each with a unique name, and have your Ajax update write the output to the iframe. The content cookie would publish the name of the most up-to-date iframe, and other windows seeing that there's fresh content could use window.open to get at that iframe (since window.open doesn't open a window if you use the name of an existing one).
Be alert to race conditions. Although JavaScript within any given page is single-threaded (barring the explicit use of web workers), you can't expect that JavaScript in the other windows is necessarily running on the same thread (it is on some browsers, not on others — heck, on Chrome it's not even the same process). I also don't know that there's any guarantee of atomicity in writing cookies, so you'll want to be vigilant.
Now, HTML5 defines some useful inter-document communication mechanisms, and so you might consider looking to see if those exist and using them before falling back on this cookie approach, since they'll work in modern browsers today but not in older browsers you're probably having to deal with right now. Still, on the browsers that support it, great!
Web storage might also be an option worth investigating as an aspect of the above, but your clients will almost certainly have to give your app permissions and it's also a fairly new thing.

How to measure HTTP cache hit rates?

Is it possible to detect HTTP cache hits in order to calculate a cache hit rate?
I'd like to add a snippet of code (JavaScript) to a HTML page that reports (AJAX) whether a resource was available from a client's local cache or fetched from server. I'd then compile some stats to give some insight on the effects of my cache tuning. I'm particularly interested in hit rates for the very first page of a user's visit.
I though about using access logs but that seems imprecise (bots) and cumbersome. Additionally, it wouldn't work with resources from different servers (especially Google's AJAX Libraries API, e.g. jquery.min.js).
Any non-JavaScript solution would be well appreciated too though.
There might be some easier way, but you could build a test where javascript loads the element and you record the time. Then when the onload event fires compare the times. You would have to test to see what the exact difference between loading from cache and loading from the server is. Or for a whole lot of items have the javascript load first record the time. Then record the onload events of everything else as it loads onto the page. This may not be as accurate though.

Categories

Resources