How would I pass data to an external script loaded with $.getScript()?

前端 未结 3 1888
青春惊慌失措
青春惊慌失措 2020-12-19 11:21

So I\'m trying to load a javascript remotely using jquery\'s $.getScript, but I\'m puzzled on how I can pass data to the external script.

I\'ve tried setting variabl

相关标签:
3条回答
  • 2020-12-19 11:22

    global variable declared in inline javascript is accessible in external javascript page loaded using $.getScript().

    0 讨论(0)
  • 2020-12-19 11:24

    I bet that your var foo='bar' is inside a function, so not visible in global scope. Try:

    window.foo = 'bar'
    
    0 讨论(0)
  • 2020-12-19 11:27

    Truly global variables will be accessible to your script. So, if they aren't, then it's probably because your variables that you think are global actually aren't. You can either move them to the top level scope or set them on the window object like Alexei suggested.

    There are other ways to share data.

    1) You can put an id on the <script> tag that loads the code and then have the code get the .src value from that tag and get the query string off the script's actual URL. I like this option, but I don't know if you can do it using jQuery.getScript() since I don't think it exposes that as an option.

    2) You can have the loading script call a function that you provide and return an object with the desired data from that function.

    3) Once the new script is loaded, you can call a setXXX() function in that script to set the state that it needs.

    4) You can set information into a cookie that the other script can read.

    5) You can encode data into a URL hash value that the other script can read.

    0 讨论(0)
提交回复
热议问题