prashant
prashant

Reputation: 999

Javascript: Include large list in js file

I have a list of city names. I want to populate this list in html select list using javascript. List has more than 1000 city names. No server request is needed. list is static.

What's the best way to include such large list into your js file? Considering performance issue, I think declaring large array in js will make it slow.

Upvotes: 2

Views: 534

Answers (3)

Kuldeep Singh
Kuldeep Singh

Reputation: 696

If only JS is involved, you can create some thing like this

var cities = [ 'City1', 'City2', 'City3', ... ];

If controller is also involved. You can form the city array in your controller assign it to view and in view file

var cities = [ echo $cityList; ];

Where $cityList is a array coming form controller.

Upvotes: 0

Include it as JSON in a script tag with a mime-type not handled by the browser, e.g.

<script type="conf/cities" id="citieslist">
['New York', 'London' ... 'Amsterdam']
</script>

The contents can then be retrieved, e.g. using jQuery:

var citylist = $.parseJSON($("#citieslist").text());

Update: An alternative method is to include the list as a simple text string with the names delimited by line feeds. This will allow you to simply use string.split() to obtain the list.

var citylist = $("#citieslist").text().split('\n');

As shown below, this is rather space-efficient.

<script type="conf/cities" id="citieslist">
New York
London
Amsterdam
</script>

Upvotes: 0

Gunslinger
Gunslinger

Reputation: 747

Include it as a javascript array. That way you can easily loop through it and populate your select box.

var cities = [ 'London', 'Paris', 'Rome' ]; 
for (index in cities) {
    var city = cities['index'];
    //add value to select box
}

If you need more than city names, you can make an array of objects:

var cities = [ { id : '1', name : 'Rome' }, { id : '2', name : 'London' }, ... ];

Upvotes: 1

Related Questions