开发者

Generate a script with php or use json

I need to know what is better/more efficient, when my page loads I need to load some elements from a database. Right now I use php to generate the proper JS in a script tag.

It looks something like this

<script type="text/javascript">
canvas = 开发者_JAVA百科$('#drawn').get(0)
c = canvas.getContext('2d');
    <? foreach ($projectArray[1] as $shape): ?>
    <?
        switch ($shape['type']): 
            case 1: ?>
                c.beginPath();
                c.moveTo(<?=$shape['x_points'][0] ?>, <?=$shape['y_points'][0] ?>);
                <? for ($point = 0; $point < count($shape['x_points'])-1; $point++): ?>
                    c.lineTo(<?=$shape['x_points'][$point] ?>, <?=$shape['y_points'][$point] ?>);
                <? endfor; ?>
                c.stroke();
                <? break;
...

This generates a script at the bottom of the page that is really long and looks something like this.

script type="text/javascript"> 
canvas = $('#drawn').get(0)
c = canvas.getContext('2d');
c.beginPath();
c.moveTo(373, 138);
...
c.lineTo(586, 242);
c.lineTo(588, 243);
c.lineTo(589, 244);
c.stroke();
c.beginPath();
c.moveTo(222, 165);
c.lineTo(222, 165);
...
c.lineTo(313, 309);
c.lineTo(261, 309);
c.stroke();
c.beginPath();
c.moveTo(81, 110);
c.lineTo(81, 110);
c.lineTo(84, 110);
...

As you can see this generates a long script based on an array passed with php based on what I pull from a db. Deep down in my heart this feels like the wrong way to do it and instead I should encode the array as json and iterate over it as a json object.

Really my question is, is it kosher to generate a script like that or should I use json and what are the advantages of doing it either way?


I would suggest JSON. You can fetch records from DB in an array and simply convert it into JSON, result will be more readable code and even faster PHP side code resulting in faster page load. Now, until and unless you profile your JS side, its hard to predict if the JSON would be faster on client side or not. AFAIK, there is no silver bullet for optimised and fast code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜