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.

3
  • 1
    Here is another SO question... different question but same idea... what-does-a-script-tag-with-src-and-content-mean Commented Jun 11, 2014 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... Commented Jun 11, 2014 at 20:14
  • Interesting and useful comments. Thank you! Commented Jun 11, 2014 at 20:59

1 Answer 1

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.

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

4 Comments

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.
Using eval() though, is generally frowned upon.
@dandavis using eval() is not recommended and is anti-pattern
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.

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.