开发者

Setting JavaScript variables before the opening <html> tag

开发者 https://www.devze.com 2023-03-28 07:30 出处:网络
I have several PHP variables that I need to transfer to JavaScript.Currently, most of my PHP code is performed as soon as the page loads, before the opening -html- tag.If I use echo to create javascri

I have several PHP variables that I need to transfer to JavaScript. Currently, most of my PHP code is performed as soon as the page loads, before the opening -html- tag. If I use echo to create javascript variables before the tag, will they be stored correctly? Are there reasons why I would not wa开发者_开发百科nt to do this?


You might not have any problems by assigning JS variables before the opening HTML tag, but if you don't, you're using some really non standards-compliant browsers. ;-)

General rule is that everything you define on a page should be either in the <head> or the <body>. Everything else should be counted as a mistake as it does not have defined behavior. Undefined behavior leads to badness.

If you put it as the first thing in the <head>, you should be fine though.


You should keep the variables in memory until the <script> tag is output in the HTML tag:

<?php
    ...

    // I want to transfer: $my_var
?>
...
<html>
    <head>
        <script>
            var php_var = <?php echo json_encode($my_var); ?>;
        </script>
        ...
    </head>
    <body>
        ...
    </body>
</html>


Use echo to create the variables inside a script tag inside the html tag. What is the problem you are having?

0

精彩评论

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