Nawaf Momin
Nawaf Momin

Reputation: 127

How to pass function as a parameter in script tag?

I'm looking for a way to pass functions as parameters to the script tag. For example, to make the following work:

<script src="http://path/to/widget.js?param_a=1&amp;param_b=3" data-myfunc={myfunction()}></script>
<script>
    myfunction() {
        console.log("hello world")
    }
</script>

And then trigger the function from the script.

Since we can pass values in attributes and capture using getAttributes : ref

Upvotes: 0

Views: 193

Answers (3)

shunyi sui
shunyi sui

Reputation: 28

Yes there is a way!

You can delete the " () "

Just turn :

<script src="http://path/to/widget.js?param_a=1&amp;param_b=3" data-myfunc={myfunction()}></script>

into:

<script src="http://path/to/widget.js?param_a=1&amp;param_b=3" data-myfunc={myfunction}></script>

And over!

Upvotes: 0

Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18538

Try this

<script>
  // move function definition above and pass function ref - don't call that function
  myfunction(){
    console.log("hello world")
  }
</script>

<script src="http://path/to/widget.js?param_a=1&amp;param_b=3" data-myfunc={myfunction}></script>

Upvotes: 1

Tachibana Shin
Tachibana Shin

Reputation: 3898

that's pretty easy however it won't be accurate as you don't know which script tag will work first or if it will be compiled using inline or not. if it uses inline your code will not work and you have to use the server to render javascript instead

here is an example using pure javascript. in my understanding you want after loading script /widget.js it will execute function stored in data-myfunc:

widget.js

if (document.currentScript) {
  const script = document.currentScript.getAttribute('data-myfunc')

  if (script) {
    new Function(`
// sandbox faker
const window = undefined;
const document = undefined;
const Document = undefined;
const Window = undefined;
// run script
${script}
`)()

  }
} else {
  console.warn('widget.js loaded inline. Not working')
}

note if you want to declare the function myFunc after the script /widget.js you have to edit my code to use events like DOMContentLoaded to make sure the function exists

Upvotes: 0

Related Questions