1

Here's a snippet for asynchronous javascript:

var bsa = document.createElement('script');
bsa.type = 'text/javascript';
bsa.async = true;
bsa.src = 'myfile.js';
bsa.test_var = 'HI!';
(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa);

I added the line bsa.test_var = 'HI!'; - I've tried to pass parameters into the myfile.js and there print out the 'test_var', but it doesn't work.

In the myfile.js, I've tried to call alert(bsa.test_var) or just alert(test_var), but neither one version didn't work.

Is there any way to pass parameters? I would like to pass parameters into the myfile.js and there according to the parameter load data the appropriate data from database.

Thank you

3
  • Are you able to bsa.src = 'myfile.js?key1=val&key2=val' ? Commented Feb 24, 2013 at 12:03
  • I am pretty sure async does nothing in that code. Commented Feb 24, 2013 at 12:03
  • Your example works for me. What does alert(bsa.test_var) display? Commented Feb 24, 2013 at 12:45

2 Answers 2

2

You do not pass parameters to scripts, you pass parameters to functions.

You will need to change your script so that it doesn't actually do anything until the functions therein are invoked, and pass the parameters at that point.

Your problem then becomes just one of figuring out when the script has completed loading, which can be done by adding a .onload handler to the <script> element object.

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

4 Comments

You can pass parameters to scripts - that may not be what he's intending to do but it can be done. papermashup.com/read-url-get-variables-withjavascript
@AInitak, could you give me an example/link on how to do that?
@NicholasPickering yes, he might be intending to pass CGI-style parameters to a remote server that then alters the JS source based on those values. That's almost never the right thing to do, though.
@user984621 you need to move up a level and describe what the goal is, not what the problem is with your apparently incorrect approach to that goal. Google for "XY problem"
0

Unfortunately you can't pass parameters to scripts.

You can use RequireJS to load your scripts. You will be notified when your script is loaded, at which time you can perform initialization using the needed custom parameters. It is not required to use AMD modules, but your code will be better structured if you do.

require('myfile.js', function (MyModule) {
    var myModule = new MyModule(customParameter);
});

Comments

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.