5

It is possible to obtain as a string the content of an external script? Something equivalent to myInlineScript.textContent?

The scenario is that I'm just starting to get into WebGL and all the tutorials I'm finding store shaders as inline <script type="x-shader/x-foo"> tags. The element itself isn't important, however — the shaders are created from plain strings. These are easily extracted from inline scripts via .textContent, but I'd of course prefer to keep my code separate from my markup.

Is there some equivalent for getting the source / content of an external script? A quick scan of the DOM docs and a Google search didn't yield anything enlightening.

Update

The WebGL shaders aren't a huge problem — there are a number of ways of getting strings in Javascript! But this isn't the only time I've encountered script tags being used to inline non-scripts and it got be curious about a better way to do it.

Ben Blank
  • 54,908
  • 28
  • 127
  • 156

1 Answers1

3

If it's on the same domain you can just do a normal ajax request for it, and get the file back as a string. This works for any kind of text file.

Also, I am not familiar with WebGL, but if your shaders are in external files then I assume the "x-shader" script type is simply a way to put them inline. Otherwise, it's just a string you pass to a method somewhere. So don't over-think this too much.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Yeah, I'm currently currently storing the shaders as [multiline strings](http://stackoverflow.com/questions/1589234/whats-the-cleanest-way-to-write-a-multiline-string-in-javascript) in my JS, but extra cruft is bugging me. I had thought of AJAX last night and rejected it, but this morning I can't think why. I'll leave the question open a while longer, but this is probably what I'll end up doing. – Ben Blank Mar 27 '11 at 16:16
  • You want a string from some external file on the same host. This is precisely what an AJAX request is for. – Alex Wayne Mar 27 '11 at 18:39
  • I was specifically interested in examining the source code of an external script already linked into the page. In my situation, I can replace the external script with an AJAX call, but in the general case, that would result in an extra server hit. So my problem is solved, but my curiosity is not satisfied. ;-) – Ben Blank Mar 28 '11 at 17:58
  • This is not an answer to the question, but a waste of a perfectly good google search. – Bijou Trouvaille Feb 24 '12 at 18:40
  • 1
    @audio.zoom that was not useful reply, but a waste of a perfectly good comment. – Alex Wayne Feb 28 '12 at 00:00
  • 1
    Disagreed. I pointed out that the answer was aimed at solving the asker's problem, rather than answering the question asked. – Bijou Trouvaille Feb 28 '12 at 15:57