How do I load a resource in Javascript?

I would like to load something like properties or XML file from my JS (webpage) (for example including a .js file in .html).

Currently I have some resources included as <script type = "resources"> blabla </script> and find them in the DOM, but I would like to externalize the resources into an additional file. How can I access the content in my JS?

Searching for "resources" and JS only gives all the C # / ASP questions.

edit: tried to copy the angle brackets so you can see my example.

+3


source to share


2 answers


If the resource is on the same domain, you can just use the ajax call from your JS file. If it's on a different domain, you must configure CORS correctly. The file you choose will be available to you as a simple txt (or whatever) if you set the contentType to the correct value in the response header.

For example, using jQuery:

$(document).ready(function() {
    $.get('/path/to/your/file.xml', function(data) {
        // Here you can do whatever you want with the data 
        $(data).find('option').each(function() {
           alert($(this).text());
        })
    });
});

      



This will warn 4 times with 1, 2, 3 and 4 as the warning text when loading this XML file:

<properties>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</properties>

      

+1


source


You can use "Ajax", that is, GET requests using XmlHttpRequest, to load resources after the initial page load.

I'm going to use jQuery (JavaScript library) to answer just because vanilla JS is a pain to worry about:



$.get("resource.xml", function(data) { xml = data; xmlIsReady(data); })

      

If you continue to process your data at xmlIsReady

. You can also explore the Deferred Object methods . I didn't make any processing errors, but you should probably have it.

+1


source







All Articles