Can I load a javascript array from an external file? - javascript

My app uses a lookup table that is embedded in the script. For ease of maintenance I would like to load this table from an external file. What is the best way to accomplish this? I am using the table to specify an image to be loaded on a click event.
var categoryTable = {
"volunteer": "d3_files/images/thunderx64.png",
"organization": "d3_files/images/cloudyDayx64.png",
"air":"nothing"
};

you can make a function in other js file that return this array.
load that file and call function to get this array.

An external .js file can contain any valid Javascript. Putting a variable assignment in it is just fine.
It will have to be a global variable for it to be visible to code in other files.

Take a look at jQuery getScript() Method:
Quoting from Jquery site:
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
If your table is JS, then this should help you. However, I think that a better approach would be to rewrite the table code and give it a JSON or XML form. It is is table, then it should be adaptable to some standard form of data representation rather than some custom JS code.

Related

How to handle large amount of HTML in a javascript library

I was tasked to create a javascript library.
The role of this library is to create a complex form with multiple choices/steps on any website. (It means that we don't have access to the website where the form is deployed.)
The code to use the library is the following :
<body>
<div id="container"><!-- Here should be inserted my HTML form --></div>
</body>
<script src="http://wwww.example.com/path/to/myLibrary.js"></script>
<script>
(function() {
var dom = document.getElementById('container');
var mb = new MLibrary(dom);
mb.initialize();
})();
</script>
Once filled, this form is finally sent to our API endpoint where it is treated.
Because of the complexity of the form, I need to create a huge amount of element using javascript. The HTML source code of the form is ~600 lines of HTML
Having this much HTML inside a .js file has proved to be ridiculously hard to maintain and horrible to read.
Because of performance purpose, I was required to avoid AJAX request as much as possible which means that I should avoid to store the HTML on the server and get it through AJAX.
If you can't use AJAX to get HTML, how can you handle a large amount of HTML inside a javascript library in order for it to be maintainable ?
I've created a very basic version of this library using JSFiddle :
https://jsfiddle.net/xd4ojka2/
I faced the same problem awhile back. Basically, I had to bundle my html with my js with Webpack. In development, all code lives in it's own file: html inside .html, js in .js, less or sass in their respective files. Then Webpack will build the app by combining all these files, giving me a build.js file (the name is configurable).
That file might be bigger than your average JS file, but it has all the stuff your app needs, meaning no AJAX to fetch HTML, or other parts of the app. Since this file will be kept in browser's cache, you need to implement a cache busting (outside of the scope of this question).
You could programmatically create HTML tags using JSON input on the fly. The JSON input for generating the markup can be retrieved using AJAX calls or stored in LocalStorage on app initialization or be lazy loaded.

django and javascript how to organize

I'm trying to figure out how to organize my javascript/django code.
So far I used to put my javascript page specific code in the same file. i.e I embed javascript in a <script> tag inside the template.
This creates a lot of mess when my JS code become large:
- django template variables {{var}} inside my JS code does not look well,
- I get an error when I try to minify it with tools like this one: http://jscompress.com/ ,
- And I just try to separate them as much as possible.
Today, in my embeded <script> tag my JS code looks like:
var app = {
func: function() {
// can I use the {% url %} tag here ?
$.post('/url/', {csrfmiddlewaretoken:'{{csrf_token}}', something:'value'} )
},
jsonFromServer: '{{pythonDict|safe}}', // I need this data structure,
};
As you can see, there are some values I need to pass form django to javascript, the most common is the csrftoken, for ajax requests. But sometimes I also pass a json dictionary that is needed for the app itself. Sometimes I want to pass the server time as well.
I'm thinking of moving the JS code to a separate file, I read that it is better way to organize like that. But I can't see how it is possible in a normal django app, without django have to render the .js files. And I believe it is better the JS file won't be served by django?
So how could I organize my JS without too much django code in it ?
I Don't know if it's "beautiful" but usually, I organize my code like that when it's about make web dev in MVC:
I put my <script> tag in the template of my page.
I write my js in an external file, traditionally in the /static/JS/my_template_name.js
As my gobal layout can have some JS code too, I make a great use of the JS modules: https://medium.freecodecamp.com/javascript-modules-a-beginner-s-guide-783f7d7a5fcc#.bjf4xwuq4
Usually, I don't have to do that.
When I need var from server in my js code, I make some Ajax calls.
But if you really want to process like that, I can suggest you to do something like this in your template:
<script>
var from_server = {{vars_from_server}};
</script>
Normally, if you pass a variable named vars_from_server to your template it will replace the placeholder between the script tags. Just think to format "vars_from_server" in a correct JS way.
After that, you will be able to access your vars in your scripts by accessing from_server variable from anywhere.

Using a webpage/web application to read and collect elements from XSL file

I have xsl page which include a number of templates cover all i need to create the webpages i want, i call the templates using nodes into another xsl file,
I need to call and collect the templates into a webpage instead of xsl using dropdown-lists.
How can i achieve that?
It seems not easy so any thoughts could help!
Thanks in advance!
I find it pretty tricky too and don't have a full answer for you.
Display the templates should be the easy part. You could catch them via XQuery, javascript as xml element from an xml file (the XSL stylesheet).
To call just some specific templates, I don't know...
One way to achieve your goal, is maybe using webServices to call xslTransform. You could do that easily with eXist for example (http://en.wikibooks.org/wiki/XQuery/XQuery_and_XSLT#Creating_an_XSLT_service). Exist embedded Webservices provide such functions (ie. calling XSLT inside web context). You have similar functionnalies in javascript (I guess...).
Maybe using XQuery (or anything else) to dynamically generate a simple template stylesheet (ie : extracting the template and create a XSLT file with only it inside) and execute it could be a solution.
Another way, may be using the mode attributes of templates. You could set an execution mode for a XSLT when launching it. But you may find yourself with one specific mode for each template...
Hope this could help.

How to load file contents from another domain using just JS?

I'm thinking of doing some online file manipulation for mobile users, the idea being that the user provides a URL to the file, then the file contents are modified by the JS, and can then be downloaded. But I haven't been able to figure out how to get the file when it's on a separate domain using just JS.
Is this possible? If so any hints or examples would be appreciated.
Just wanted to add that part of what I wanted to do was make it available without my hosting it. I'm thinking of something like a a file they can host somewhere,and then all of the bandwidth is their own...and that of wherever they are getting the file from of course.
The only way to load contents of a file on another domain is from within a <script> tag. This is how JSONP works. Look into getting your target file into this format.
The other way would be to use a local proxy. Create a web service method that loads and returns the contents of the file, then call that locally using your favorite JavaScript framework.
Depending on how you think of public webservices, and within some limitations I'm still mapping, you can do this using an ajax call to YQL, like so.
(will expand the answer later).
http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20data.uri%20where%20url=%22http://t3.gstatic.com/images?q=tbn:ANd9GcSyART8OudfFJQ5oBplmhZ6HIIlougzPgwQ9qcgknK8_tivdW0EOg%22
One of the limitations of this method is file size, it currently tops out at 25k.

Is it possible to read values from a JSON object stored in another javascript file?

I am working on a custom piece where I am dynamically building very specific tables and writing them out using javascript after an AJAX call. I am trying to avoid writing custom code for each of these tables by coming up with a standard layout where I customize the layout via values in a JSON object stored in my current javascript file. Is there anyway I can store this object in another file and read it as if it were a properties file to make things neater?
Javascript stored in separate files can be referenced as long as it is not wrapped somehow in a function, if so then you would need to reference that function. Thus JSON objects stored in separate files can be referenced - they are just Javascript (everything is an object in Javascript).
SO if you have simple object, or complex JSON:
myobject = "fred";
myobject2 = "wilma";
They can still be referenced, if they are in the same file, or not.
alert(myobject + myobject2);
shows "fredwilma"
Of course JSON objects would be more complicated, but the principle still applies.
You need to dynamically load your additional javascript files. Here is a good article that portrays how to do that using static / dhtml methods.
Like m_oLogin said, you can dynamically load the additional scripts. Instead of doing as the article suggested, you can also use jquery to load the scripts -
$.getScript('script/loaded-script.js'), function() {
//action to execute after script is loaded
});

Categories