最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

import - How to include text file into javascript - Stack Overflow

programmeradmin1浏览0评论

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 */

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 */

Share Improve this question edited Jan 2, 2012 at 21:59 bobbymcr 24.2k3 gold badges57 silver badges67 bronze badges asked Sep 15, 2011 at 15:15 mihaimihai 38.5k11 gold badges62 silver badges89 bronze badges 1
  • Load text and do what with it? – Zirak Commented Sep 15, 2011 at 15:18
Add a comment  | 

3 Answers 3

Reset to default 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.

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

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>
发布评论

评论列表(0)

  1. 暂无评论