I have some set of preset values associated with a item in dropdown list. Since the list is large I don't want to store them in js file with if else block.
I found that I can store them in json format but it seems like jquery.getJson() makes http get request for this even if file is stored locally. This may add some delay in fetching values. In my case instant response is really important because these vales will be changed during realtime sound editing feature.
I was thinking may be I can load these values on page load itself and store it in some variable and then when required do if else to find particular value. Though I am not really sure if this is right way to do. Please suggest.
Have you thought of DOM storage.
Have a look at this and check it serves any of your purpose.
Well, given your requirements, You'd have to load them by including js files.
In main html, you'd have:
<script>
var GlobalData = {};
</script>
<script src="albums.js"></script>
<script src="songs.js"></script>
...
Then, in albums.js (or any other file) you'd have:
GlobalData.albums = [
//... your data here
];
Then, to access this data when you need it, just do it straightforward
alert(GlobalData.albums.length);
However, if the amount of data is big, it's better if you don't have it always in memory. You could dynamically load it or save it on localStorage.
Cheers
You mentioned jQuery, so I guess $.data will do the trick - http://api.jquery.com/data/
Related
Ok, I've been wondering what I'm doing wrong with a Knockout web app I'm trying to put together.
Here is the code excluding the AJAX service with my MVC PHP interface.
my.js = namespace declaration that I use for my app
data.js = contains static data which works to load the data into the view (leftPanel.php)
appViewModel.js = call the functions that loads the data from PHP server and declare the view model.
So, basically, here is the issue:
I've an AJAX Service that works and get the data as show in accounts_JSON.txt and currencies_JSON.txt. The JSON is well formatted and in the text files, I've only added returns to make it easy to read.
In appViewModel.js, the "getCurrencies" and "getAccounts" methods are called and work properly: iterate through the JSON data and put it in the specified array.
Then, at the end of appViewModel.js, I log in the Chrome console each step because I can't find out why "my.app.data.currencies" and "my.app.data.accounts" are logged as empty when they are not (screenshot_chrome_console.png).
Those arrays are populated before the ko.applyBiddings so if I were to use "my.app.data.currencies" and "my.app.data.accounts" to populate the view, it should work but it doesn't. Only the static data "my.app.leftPanel.currencies.list" and "my.app.leftPanel.accounts.list" works.
What am I missing? I really can't see!
Thanks a lot for your help :)
Well, I've solved my issue :) Thanks to this post (from Irakli Nadareishvili).
My problem was definitely the loading method of the data retrieved via AJAX. Using Underscore to load the currencies and the accounts first and when, and only when all is loaded, filteredAccounts is loaded since I need the full list of accounts.
Here is the final and cleaned-up code in case anyone is interested or stumble on the same problem.
Happy coding to all!
Often the Javascript on a webpage will need to be able to access variables that are known on the server. For example, the user's username. Suppose that we don't want to make a JSON/XML request as that would increase the complexity unnecessarily and also the number of page hits. We want to send the data along with the html/Javascript.
One way to send the data would be to inject it into the Javascript.
var x={{username}};
Another idea would be to create a meta item in the head and store the data there and then use jQuery (or equivalent) to retrieve it.
Is either of these methods preferable to the other or are there any other methods that I should consider?
Is either of these methods preferable to the other or are there any other methods that I should consider?
I don't think there's a single right answer, and certainly I've heard lots of contradictory opinions on this subject, but choosing from the two methods you mention I'd go with injecting the values into JavaScript because I find it easier.
But since you asked for other suggestions you can kind of combine the two ideas: instead of meta items, your server-side code can just insert a single <script> element in the <head> to store the data in a variable that can then be accessed directly from any of your other scripts (including scripts in multiple source files). You can stick all of your data in a single object to avoid lots of globals:
<html>
<head>
<script>
var dataFromServer = { /* all your server data here */};
</script>
<script type="text/javascript" src="somelibrarycript.js"></script>
<script type="text/javascript" src="someotherscript.js"></script>
<script>
if (dataFromServer.someProperty) {
// someProperty provided above so do something with it...
}
</script>
</head>
etc...
This approach has the added advantage that the server-side code is essentially just producing JSON (that becomes an object literal if included directly in the page source) so if you later decide to start using some Ajax you'll already be almost there.
I would just have a element in the head which declares a well-named global object containing your information. Something like :
<script type="text/javascript" >
this.blah = this.blah || {};
this.blah.userinfo = this.blah.userinfo || {};
this.blah.userinfo = {
"username" : "UserName42"
"gender" : "Male"
};
<script>
The top two lines just initialise your global object. Since it's global, we use "blah" to namespace it.
What you are suggesting is totally fine. For example Jeremy Ashkenas, creator of CoffeeScript, Underscore.js and Backbone.js suggests to do exactly the same in Backbone docs
<script>
Accounts.reset(<%= #accounts.to_json %>);
Projects.reset(<%= #projects.to_json(:collaborators => true) %>);
</script>
I think that a question is a bit convoluted, since, in my experience, you rarely rely on static/pre-created HTML pages for sites that have accounts, user privileges etc.
Normally, such a site/application relies on some sort of "Server Pages" technology - ASP, JSP, PHP (or manages all of this through AJAX requests) - which would allow you to write some sort of tag/server code similar to <%=request.getAttribute("userName")%> - that, when compiled/interpreted by the server, will inject the username for you in the place in your page you intend it to be.
If, for some reason, you claim that it's not the case in your application and you deliver pure pre-created or static HTML to your users - then, indeed you would have to do one of the following:
1.AJAX request that retrieves the username
I think that your argument that
that would increase the complexity unnecessarily and also the number
of page hits
is not a valid one. Correctness of use of technology should prevail over (perhaps non-existent) performance gain. I also don't see that as a complexity increase, on the contrary - you could separate the "user" logging in part into a module and reuse it elsewhere.
2.Inject JavaScript (or use meta-tags)
and this one I am not entirely sure how would you do that and maintain your page after that...
I would like to use localStorage to 'cache' some JS and CSS files in a web app that is primarily used on mobile devices (i.e., bandwidth restrictions). I'm thinking it would work something like this:
The page loads with a small setup.js containing code that checks localStorage to see if bigScriptFile.js has been stored previously.
If it's not stored, bigScriptFile.js is downloaded and stored for the next visit.
If it has been stored, then bigScriptFiles.js is read from localStorage and loaded/run as if it was downloaded like a normal file (i.e., <script src="http://example.com/bigScriptFile.js"></script>)
What I'm not sure how to do is step 1.1 -- storing the JS file. (I know that I can only store strings in localStorage and I know how to use JSON.stringify().)
Surely it's not as simple as using escape():
localStorage.setItem('bigScriptFile', escape('myJScode')) to store, and
unescape(localStorage.getItem['bigScriptFile']) when retrieving
Even if it is that easy, how do I use JS to get the contents of bigScriptFile.js as a string? Perhaps by making an ajax call to a PHP script that returns the contents?
You should rather put the correct cache headers on js files or look at the HTML5 cache manifest.
W3C specification.
Have you seen http://addyosmani.github.com/basket.js/ might work for what you intended to do
to initialize a javascript loaded grid, I need to pass a list of values from controller/gsp. Since the javascript is activated once the page is rendered/loaded, there may not be a direct way to do it. 2 possibilities
1. do an ajax call, and retrieve the list of values from the server
2. store the list in html as a hidden element, and read it from javascript.
option 2 seems better as it avoids few calls back to server. So, which control should I use for a list of values? Any jQuery code snippet to read it back into array/list.
thanks in advance.
It depends on the size of that data. It it's small enough, you could embed it in the page. For example, to populate a calendar with events, I used something like:
<div id="calendar" data-events="[/* event list */]"></div>(the data-events attribute contained a JavaScript array of event objects in JSON format)
However, if you're talking about a huge amount of data, loading it (possibly in chunks) asynchronously after the page load (or when the document is ready) could increase your app's performace and make it more interactive (i.e. I don't want to wait and load that data if the next thing I'm gonna do is navigate away)
Does that answer your question?
You can directly write JavaScript from the server side. I don't know about grails, but here's a very simple example in php:
<script type="text/javascript">
var someVar = "<?php echo $someServerVar;?>";
</script>
Sure, this example is very simple, but you get the idea. And most languages will have some sort of function that escapes JavaScript strings (basically turn " into \" and new lines into \n).
If you put a script like that at the top of your <head>, then those variables will be accessible from all other scripts on the page.
if im loading data for the markers from a database do i write the output queried from the db into a javascript file or is there a cleaner way of doing it?
thanks
Yeah, writing to a file is a good way to do it. Just write the data as JSON. Your file would look like:
var map = {waypoints:[...]};
And then you can do:
for(var i=o; i<map.waypoints.length; ++i) {
addWaypoint(map.waypoints[i]);
}
I actually do some static caching of nodes using this method: http://www.trailbehind.com/site_media/javascript/gen/national-parks.js
We use that set of National Parks a lot, so we cache it. But we also have urls where you can fetch JSON for a node on the fly, such as: http://www.trailbehind.com/map/node/7538973/632/735/
This URL gets the map for node 7538973, and specifies the dimensions of their map in pixels as well.
The needed Javascript can of course be wrapped in whatever language you prefer to use, see e.g. pymaps for a Python example. While pymaps is actualally inserting the JS code into an HTML template, if you're writing a web app you can perfectly well choose to serve that JS code on the fly at an appropriate URL and use that URL in a <script> tag in your pages.
Depending on the size of your application, you may want to consider printing out plain javascript.
I have a map that uses server-side clustering, so markers update frequently. I found that parsing JSON markers slowed the app significantly, and simply wasn't necessary.
If speed is an issue, I'd suggesting removing all of the unnecessary layers possible (JSON, AJAX, etc.). If it's not, you'll be just fine with JSON, which is cleaner.
I agree with Andrew's answer (+1).
I guess the only point I would add is that rather than including some server side generated JavaScript, you could use an AJAX request to grab that data. Something like:
var request = new Request.JSON (url: 'get_some_json.php',
onSuccess: function(data) {
// do stuff with the data
}).get ();
(This is a Mootools AJAX thing, but you could use any kind of AJAX request object).
Edit: ChrisB makes a good point about the performance of parsing JSON responses and re-reading my answer I certainly didn't make myself clear. I think AJAX requests are suitable for re-requesting data based on parameters generated by user interaction. I guess an example use case might be, a user filtering the data displayed on the map. You might grab the filtered data via an AJAX/SJON request rather than re-loading the page.