How can I access URL parameters in Javascript loaded asynchronously by require.js?
-
27-10-2019 - |
Question
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.
Solution
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.