Home > database >  How to pass function as a parameter in script tag?
How to pass function as a parameter in script tag?

Time:02-04

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

CodePudding user response:

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>

CodePudding user response:

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!

It's my pleasure to help you!

by the way if you are interested, please help me also:

The is my question

CodePudding user response:

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

  • Related