7

Is there any way to load some text from another file into javascript, without server side code?

I was thinking to use another element to hold the text inside some comments, but I don't know how to read it's source code with javascript.

Something like:

<script src="myfile.js"></script>

<script> function readMyText() { ... }</script>

In myfile.js: /* some text */

1
  • Load text and do what with it? Commented Sep 15, 2011 at 15:18

3 Answers 3

12

You can put anything you want into a script tag if you give it a "type" that's not something the browser understands as meaning "JavaScript":

<script id='Turtle' type='text/poem'>
  Turtle, turtle, on the ground;
  Pink and shiny - turn around.
</script>

You can get the contents via the "innerHTML" property:

var poemScript = document.getElementById('Turtle');
var poem = poemScript.innerHTML;

Here is a jsfiddle to demonstrate.

That trick is popular lately with people doing client-side page building via templates.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer, this works nicely when the text is added within the script tag, but if i change this to <script href="turtle.txt"></script> I can't access the contents :( . I'll edit the question to reflect this.
Ah yes, that's true. Well, you could try pulling the script into a hidden <iframe> and then read it out of that.
2

Without using ajax or any server code... sorry mate but you can't :(

Comments

0

Building on Pointy's answer, to import from local files do this:

<script src="foo.txt" id="text" type="text">
</script>

You could also use this to target an external file:

<script src="http://foo.txt"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.