Ben Blank
Ben Blank

Reputation: 56624

Get the source (code) of an external script?

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.

Upvotes: 5

Views: 2061

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187242

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.

Upvotes: 3

Related Questions