如何访问 require.js 异步加载的 Javascript 中的 URL 参数?
我正在使用 RequireJS 在我的应用程序中加载模块。我需要将在index.php 获得的URL 参数传递给主模块。我可以看到有几种方法可以做到这一点,但我更喜欢索引中唯一的东西本质上仍然是这样的:
因为 RequireJS 说它更适合优化。我当前的解决方法是将原始 require 调用放入索引文件中,并使用那里的 URL 参数。有更好的办法吗?
作为参考,我在服务器端使用 PHP,如果这有帮助的话。
I'm using RequireJS to load the modules in my application. I need to pass a URL parameter that I get at index.php to the main module. There's a couple ways I can see to do this, but I'd prefer if the only thing in the index was still essentially this:
<script type="text/javascript" data-main="scripts/main" src ="scripts/require-jquery.js"></script>
because RequireJS says it's better for optimization. My current workaround is to put the originating require call in the index file and use the URL parameter from there. Is there a better way?
For reference, I'm using PHP on the server side, if that helps at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要将参数从 GET 传递到脚本,您有以下三种选择:
使用 $_SESSION 存储值并动态编辑主 js 文件。
这将导致大得离谱的开销,并增加很多不必要的共谋(更多共谋=>更多错误)
添加此代码 http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
到您的主模块以通过 javscript 检索参数。
使用 PHP 生成一个小型 Java 脚本(使用 $_GET)来设置值。
从理论上讲,这比其他选项更快。
选项 2 和 3 之间的速度不应有显着差异,因此只需选择符合您需求的选项即可。
如果主模块是经常更新的第三方组件,我会选择第三个选项,因为这样您就不必每次拉取新版本时都更改主模块。
如果您想设置基于用户的默认值,您应该坚持使用选项 3,以便更轻松地访问数据库和用户设置。
我希望这有帮助。
编辑:
如果您的主模块在加载所有脚本之前不需要该参数,您可以在额外的模块中使用选项 2 中的脚本来设置主模块中的值。这也可以解决更新问题。
To pass the parameter from GET to your script you have three options:
Using $_SESSION to store the value and dynamicly edit the main js file.
This will result in an ridiculously large overhead and add a lot of unnecessary complicity(more complicity => more bugs)
Add this code http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
to your main module to retrive the parameter via javscript.
Generate a small java script with PHP (using $_GET) to set the value.
Which theoretically is faster then the other options.
There shouldn't be a significant difference in speed between option 2 and 3 so just pick what matches your needs.
If The main module is a third party component that is often updated I would pick the third option because then you do not have to change the main module everytime you pull a new version.
If you want to set an user based default value you should stick with option 3 to have an easier access to you database and user settings.
I hope this helps.
EDIT:
If your main module does not require the parameter before all scrips are loaded you can use the script from option 2 in an extra module which sets the value in your main module. This would solve the updating issue, too.