1

Just out of sheer curiosity, I'd like to know if there's a technique for passing things (most likely a javascript object) to external javascript within the script tag that loads that script.

<script type="text/javascript" src="example.js">
{example:'something like this'}
</script>

I'm almost certain I've seen this done somewhere once before. I find it very tidy and would like to be able to do it for libraries i'm writing so users can pass in simple options without needing to make another script.

Wray Bowling
  • 2,346
  • 2
  • 16
  • 19
  • 1
    Here is another SO question... different question but same idea... [**what-does-a-script-tag-with-src-and-content-mean**](http://stackoverflow.com/questions/6528325/what-does-a-script-tag-with-src-and-content-mean) – Ballbin Jun 11 '14 at 19:59
  • 1
    one problem: it can be hard to find the tag later if the user downloads and re-hosts the js file. since defer/async came into play, you can't count on the last script[src] being "yours" anymore... – dandavis Jun 11 '14 at 20:14
  • Interesting and useful comments. Thank you! – Wray Bowling Jun 11 '14 at 20:59

1 Answers1

1

As with what the Question Ballbin has posted says, "It should be avoided.".

But, a different way you can do it is with another script tag.

Like this:

<script>var test1 = "Testing";</script>
<script type="text/javascript" src="example.js"></script>

The example.js file should now be able to read the contents of test1.

frosty11x
  • 205
  • 1
  • 8
  • the reasons for avoiding it are wrong, mainly that browsers don't execute the code by default. you have to find the tag and eval() the text of it. – dandavis Jun 11 '14 at 20:12
  • Using eval() though, is generally frowned upon. – frosty11x Jun 11 '14 at 20:13
  • @dandavis using `eval()` is not recommended and is anti-pattern – frogatto Jun 11 '14 at 20:14
  • 1
    eval() is frowned upon for being slow. if you add an external script, eval() is still called on the script body once it loads. if the eval avoids an http connection, and there's not a lot of code to parse, the textContent+eval can faster than doing it conventionally. there are other problems with this "template" approach, but eval itself is of little concern. it's also nice because you can mod the text before parsing it, so that you can for example, run coffeescript, parse yaml into a config, etc: it need not be js. – dandavis Jun 11 '14 at 20:16