Reputation: 48463
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
Upvotes: 1
Views: 535
Reputation: 3256
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);
});
Upvotes: 0
Reputation: 339896
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.
Upvotes: 2