Pass vars to JavaScript via the SRC attribute

2019-01-02 21:14发布

In my HTML file I have linked to the JS with:

src="myscript.js?config=true"

Can my JS directly read the value of this var like this?

alert (config);

This does not work, and the FireFox Error Console says "config is not defined". How do I read the vars passed via the src attribute in the JS file? Is it this simple?

7条回答
梦醉为红颜
2楼-- · 2019-01-02 22:02

Whether or not this SHOULD be done, is a fair question, but if you want to do it, http://feather.elektrum.org/book/src.html really shows how. Assuming your browser blocks when rendering script tags (currently true, but may not be future proof), the script in question is always the last script on the page up to that point.

Then using some framework and plugin like jQuery and http://plugins.jquery.com/project/parseQuery this becomes pretty trivial. Surprised there's not a plugin for it yet.

Somewhat related is John Resig's degrading script tags, but that runs code AFTER the external script, not as part of the initialization: http://ejohn.org/blog/degrading-script-tags/

Credits: Passing parameters to JavaScript files , Passing parameters to JavaScript files

查看更多
登录 后发表回答