Ok, so im trying to work out the fastest way of storing data on my page without slowing the page load:
- I need to store information in the page to be later used by jquery.
- My page is an events page and i want to attach data to each event anchor.
- there are 100+ events to attach data to.
The events anchors are created with开发者_C百科 a php loop, so i could create the data elements within this loop using either
- use un-semantic tags ie rel="some_data"
- create a jquery.data() for each iteration of the loop
or i could run the loop again, separately, this time inside script tags with jquery.data();
would really appreciate any thoughts on this!
A possibility would be to generate, on the server-side, a Javascript array or object that contains all the events, and inject it into the page as a Javascript variable.
Basically :
- On the PHP side :
- Build the array of events
- Transform it to Javascript, using
json_encode
- Inject it into the HTML page.
- And, later, on the JS side :
- Just use that Javascript variable.
Great thing with that solution it that is work for almost any possible kind of data, is quite fast, and quite easy to develop.
The generated HTML+JS code would look like this :
<script type="text/javascript">
var myArrayOfEvents = [ ... ];
</script>
And it could be generated with some PHP code like this :
<script type="text/javascript">
var myArrayOfEvents = <?php echo json_encode($myEvents); ?>;
</script>
Of course, up to you to :
- Define the structure you want for your events
- Build it in PHP
- Use it in Javascript
精彩评论