I have an application where the application's user relates to an HTML page during the application's runtime.
During runtime, the HTML file is being continuously updated. In order to handle every update, the HTML file is being refreshed at a fixed interval.
Is there any other better way to achieve this with more efficiency and/or to hide the refreshing technique from the user's perspective?
Any help will be greatly appreciated.
If what you're doing doesn't involve retrieving data from a server, and instead involves some kind of process that occurs on the page itself, like a clock, I would use setInterval
setInterval(function(){myFunction()},1000);
This would call myFunction() every second, and inside of that function you can change visual elements as appropiate.
You may also want to consider using a Javascript MVC framework such as Backbone.js or Angular.js, which handle changing the appearance of html elements mapped to javascript variables over the lifetime of an application for you.
From your question it sounds as if your updating the HTML file on the server in response to user actions. I'm guessing that's not literally what you meant. If it is, though, there are almost certainly better ways to do what you want to do -- depending on what, exactly, it is.
If you are just showing new information to the user, you will want to use Javascript to update the page's DOM. The easiest way for a beginner to do that would be to start by looking at jQuery tutorials. With Javascript (possibly aided by jQuery) you can easily update the content of any part of your page, without needing to actually change the original HTML file in any way.
If you want the page to be updated for everyone who visits it at a later date, then you need to put the new information in a database, and get the content from the database when you the page is requested or loaded.
It would greatly help if you specified exactly what you were trying to do.
Related
I'm working on a real-time JavaScript Application that requires all changes to a database are mirrored instantly in JavaScript and vise versa.
Right now, when changes are made in JavaScript, I make an ajax call to my API and make the corresponding changes to the DOM. On the server, the API handles the request and finishes up by sending a push using PubNub to the other current JavaScript users with the change that has been made. I also include a changeID that is sequential to JavaScript can resync the entire data set if it missed a push. Here is an example of that push:
{
"changeID":"2857693",
"type":"update",
"table":"users",
"where":{
"id":"32"
},
"set":{
"first_name":"Johnny",
"last_name":"Applesead"
}
}
When JavaScript gets this change, it updates the local storage and makes the corresponding DOM changes based on which table is being changed. Please keep in mind that my issue is not with updating the DOM, but with syncing the data from the database to JavaScript both quickly and seamlessly.
Going through this, I can't help but think that this is a terribly complicated solution to something that should be reasonably simple. Am I missing a Gotcha? How would you sync multiple JavaScript Clients with a MySQL Database seamlessly?
Just to update the question a few months later - I ended up sticking with this method and it works quite well.
I know this is an old question, but I've spent a lot of time working on this exact same problem although for a completely different context. I am creating a Phonegap App and it has to work offline and sync at a later point.
The big revelation for me is that what I really need is a version control between the browser and the server so that's what I made. stores data in sets and keys within those sets and versions all of those individually. When things go wrong there is a conflict resolution callback that you can use to resolve it.
I just put the project on GitHub, it's URL is https://github.com/forbesmyester/SyncIt
In Backbone.js, model loading and saving is done via ajax calls. However, are there any best practices to loading the initial collection on page load without having to pull this down via ajax? I'm trying to do as much server side rendering as possible up front.
In the past, I've seeded the html with a javascript variable containing a json string of the initial data state so it can be rendered server side, but I'm not sure if this is a good practice.
Don't know if it's necessarily the best practice, but this method of seeding the html with a json object (not a json string as you described it, right?) is certainly my preferred way of doing initial loading. Not only for the (obvious) reason that it removes the delay of waiting for the initial AJAX call to return, but also because the one less open connection frees the browser to load something else instead (like an img src or whatnot), getting you to document.onLoad slightly sooner.
It's recommended that, when using this method, you put the said variable in a script tag at the bottom of the body (i.e. not in the head section), in order to give the static html elements on the page a chance to load and render first. The json data is ready when document.onLoad fires.
From Backbone docs, initialising models in script tag is not a bad practice. In my current project I decided to set only plain objects inside window.projectData, to be able to init Backbone models in external javascripts.
<script>
;(window.projectData || (window.projectData = {})).modelName = {/* value */};
</script>
The approach you select will probably depend on how much data you're planning to load and how that data will be used within the page.
If most of the required data will not ultimately end up rendered on the page, bootstrapping the initial state into a javascript variable might not be a bad route.
If the data is directly related to the presentation of the page, however, you might prefer to parse a pre-rendered DOM for the initial state of the backbone application. The obligatory word of caution is that this kind of parsing will be somewhat slower, especially for large data sets.
If you do end up opting to parse pre-rendered content, I put together a small jQuery DOM parser a while back that might prove useful for mapping the presented content into a Backbone-ready form.
I'm building an AJAX 'web application' where, once the UI is loaded, calls to the server are for 'data exchange' only. As a result a lot of UI manipulation will be done using Javascript. Lets say the Javascript retrieves some data consisting of multiple fields from the server using AJAX. To put it on the screen I can think of multiple approaches -
Call methods like createElement() and appendChild() to build an interface to display the retrieved data
Populate the .innerHTML for the container element then for every data field lookup a container in the newly added HTML and populate it. The data that goes into .innerHTML could be stored in a JS variable or contained in a hidden node, or fetched using a seperate AJAX call.
Have the interface stored in a hidden node. Clone it (using cloneNode()) and put it in the actual container (using appendChild()) and then populate it with fields like in method 2.
and there are probably more ways.
Could you share pros, cons and possible gotachas in these approaches from cross-browser support, performance and coding complexity point of views?
Somewhat related question: Is client-side UI rendering via Javascript a good idea?
Thanks.
ok, let's start off:
Use toolkits
First you would want to invest time learning a JS toolkit. While others suggest native JS is good (which it really is), but you would not want to waste time on building apps that don't work cross-browser or spend too much time testing it. People in the community have invested their time in doing that for you. Show some love to the open community and use their product. I personally use jQuery, but there are others like Dojo and YUI.
But still use native JS whenever possible. It's still faster.
Structure your code
After a toolkit, you need some structure. BackboneJS will take care of that. It's to structure your code so that your code is reusable and well.. won't end up as spaghetti on your screen. Other tools like RequireJS are also useful for those scripts that need other scripts to run.
Templates: From strings to elements
Then, with that, you now have a toolkit but you still need to build the interface. It's better if you use a templating engine like Mustache or Handlebars. These render templates for your UI from strings (yes, plain strings of HTML). Just send over your template data from the server, store it in your app (in a variable or browser localstorage), and reuse it as necessary. No need for cloning hidden nodes!
Don't touch that DOM
As for approaching the DOM, you should touch the DOM only when necessary. DOM is slow, manipulating it is he** slow! that means you should avoid unnecessary animations, avoid excessive element append and remove, as well as changing styles. Check this article about avoiding too much reflow and repaints. Face it, the user won't event notice the round corners of your boxes, or the gradient background and don't even care if you did a slide animation or a fade-out. What they want is to get the job done and not adore the fireworks display.
Also, remove anything that isn't on screen. You might end up having 20% content on screen, and 80% off screen - a waste of memory.
Cache: fetch once, store, use infinitely for later
Now, your app is getting heavy and you want to shave off some HTTP requests. You can do this by caching. I usually use caching mostly on the templates so that every new UI, you don't need to load again from the server. You can do this by storing stuff in an object. you can go a little further and use the browser's localStorage when available.
Caching isn't all for the network. Let's say you have some complex calculations you want to use later, or some text from an unfinished form, use the cache for that too.
Avoid HTTP requests (or at least lighten them up)
While lightening up your app by using AJAX, you will inevitably be tempted to use AJAX just about anywhere - don't abuse it. Often times i see people who aggressively poll the server (every half-second or less). This not only strains the server (too many requests), but also the browser (wasting processing cycles) and the network (bandwidth). There are several practices done these days to avoid added HTTP requests:
Image Spriting - The art of placing a lot of images into one image and using background-position to change the image. Surely beats 100 individual HTTP requests
Use JSON for textual data - AJAX was meant to use XML.. then came along JSON that was a fat-free, platform-independent format of strucured data.
Do not return HTML-formatted data - With exemption of templates, which are HTML strings, you should never return HTML-formatted data over the wire. Have JS do JSON+templates on the client-side instead.
I'm building a similar app (Lightweight CMS)
In my view the approach you take will be dependent on the complexity of data that you are sending from the server > manipulating on the client side > and returning back to the server and db.
The cms that I'm working on is very basic and does not require heavy-duty manupulation on the client side. TinyMCE is as far as it will go.
Initially I was building the client admin area by echoing <input> from php and then collecting the data by parsing the DOM, converting to JSON and AJAX it back to the server (I found this code very helpful)
That of course required the user to hit "save" after editing or adding new data.
I later on decided that I needed something even more responsive and simpler than that so I'm now re-implementing everything for Jeditable which AJAXes the data as soon as the client hits "OK" on that particular field. No "main save" required.
To conclude it's really an area that is pretty uncharted. I mean, it appears to me that people in the industry do not like to blur that line between back-end and front-end and find "one solution" that will do the entire DB>SERVER>CLIENT>SERVER>DB operation.
I'd love to see how you solved your problem.
Just my 2 cents.
I am writing my first Rails app using the twitter gem. I'm simply retrieving search results and trying to cycle through them individually every 5 seconds or so.
My thought was to create a variable and have this variable represent the array index and simply update this variable dynamically with Javascript (every 5 seconds or so). What's the best way to achieve this on the client-side? AJAX? Javascript?
Does this make sense? I will be glad to provide more context if helpful. Thanks.
Sounds you're trying to build a "recent tweets" marquee of some sort. Without knowing your requirements, you could try simply loading the ten most recent tweets in Rails, putting them in ten hidden divs, and then using jQuery just to cycle through the different tweets on the page.
If it is a requirement to "update" the most recent tweets without the user refreshing the page, then yes, you'd probably need an AJAX call.
It's hard to tell what you think you're asking: by the time your JavaScript is executing the server is no longer involved.
If you want to update some sort of count on the server side and persist it in a meaningful way, you can do so via Ajax.
What are you actually trying to do, though?
Ruby runs on the server while JavaScript (usually) runs on the client.
The Ruby generates an HTML document (perhaps with embedded JS) and the server delivers it to the client.
At that stage the Ruby has finished executing. The only way to do anything further with Ruby would be to make a new HTTP request to the server. This could be done by following a link, submitting a form, setting location.href, using XMLHttpRequest or numerous other techniques.
This would cause the Ruby program to be executed again (or a different one to be executed) which would do whatever it did with the input data.
You cannot simply "set a variable" on the server from the client.
In my particular case, I used ruby's .to_json method to convert the data and then manipulated it with javascript. This gave me the flexibility to loop through the data pretty seamlessly. Atleast it seemed to work for my particular situation. Thanks for the help guys!
I'm creating a web application that allows users to make changes through Javascript. There is not yet any AJAX involved, so those changes to the DOM are being made purely in the user's local browser.
But how can I make those DOM changes occur in the browser of anyone else who is viewing that page at the time? I assume AJAX would be involved here. Perhaps the page could just send the entire, JS-modified source code back to the server and then the other people viewing would receive very frequent AJAX updates?
Screen sharing would obviously be an easy work-around, but I'm interested to know if there's a better way, such as described above.
Thanks!
You are talking about comet, for an easy implementation i'd suggest:
http://www.ape-project.org/
and also check these:
http://meteorserver.org/
http://activemq.apache.org/ajax.html
http://cometdaily.com/maturity.html
and new html5 way of it
http://dev.w3.org/html5/websockets/
Hope these help.
Max,
Ajax will have to be involved. If i may, I'd like to suggest jQuery as a starting point for this (i know you didn't tag as such, but i feel it'd be appropriate, even if only to prototype with). the basic semantics would involve running the ajax request in combination with a setInterval() timer to fire off the ajax request. this could be done in jQuery along the lines of:
$(document).ready(function() {
// run the initial request
GetFreshInfo();
// set the query to run every 15 seconds
setInterval(GetFreshInfo, 1500);
});
function GetFreshInfo(){
// do the ajax get call here (could be a .net or php page etc)
$.get('mypageinfostuff.php', null, function(data){$('#myDivToUpdate').html(data);});
}
that's the basic premise... i.e the webpage is loaded via GetFreshInfo() initially straight away, then it's requeried every 15 seconds. you can add logoc to only refresh the div if there is new data there, rather than always updating the page. as it's ajax, the page won't freeze and the process will be almost invisible to the user (unless you want to flag the changes in any way)
Hope this helps
jim