Passing JavaScript data to a page, best practice?
I am writing a web application where I need to pass some custom data to the JS application on page load. I have identified 3 different approaches and I am wondering what is the best practice regarding this. The data is not particularly sensitive, but it would be better if it were slightly more secure than others.
1. Load data asynchronously
Using something like $.ajax()
. I don't like this approach because it usually leads to the whole "loading" phenomenon, and I would like to avoid it. Prepare data except for a separate call.
2. Write the data to the page.
This can be done by doing something like this
<script>
var userdata = { somekey: somevalue }
</script>
3. Make a request using script tags
This can be done by doing something like this
<script src="server/getdata"></script>
I understand that this is similar to the first approach as it makes a different request to the server.
My question is, is any of the three approaches superior or better from a security standpoint. I understand that all 3 methods are not particularly safe, especially since they can be easily sniffed anyway, but is any of the above methods better practice than the other 2, and why?
source to share
Of the ones you gave, 2 is best, just for the reasons you said. However, I would not add a new global to it. Rather, I would do:
<script type="text/javascript" src="application.js"></script>
to create someGlobal
(by the way), then:
<script>
someGlobal.userdata = { somekey: somevalue }
</script>
Other pairing methods with the same benefits:
- data attributes . This is
data-
. You can put arbitrary data associated with certain elements (sometimes certain elements make sense, otherwise you can usebody
). - Hidden form fields.
source to share