admin管理员组

文章数量:1417651

I am writing a custom made plugin that will have advanced JS scripts, in order to preload relevant data i am localizing scripts.

PHP

$post_array = my_function_to_get_my_data();
wp_localize_script('registered_script', 'serverData', array( 'posts' => $post_array ) );

JS part:

jQuery(document).ready( function($){
    $.each( serverData.posts, function( id, content ){
      console.log( content );
    }
});

Will the data passed via wp_localize_script be up to date on the client side ( meaning that caching will not be an issue ). ?

I am writing a custom made plugin that will have advanced JS scripts, in order to preload relevant data i am localizing scripts.

PHP

$post_array = my_function_to_get_my_data();
wp_localize_script('registered_script', 'serverData', array( 'posts' => $post_array ) );

JS part:

jQuery(document).ready( function($){
    $.each( serverData.posts, function( id, content ){
      console.log( content );
    }
});

Will the data passed via wp_localize_script be up to date on the client side ( meaning that caching will not be an issue ). ?

Share Improve this question asked Aug 1, 2019 at 6:29 Jess_PinkmanJess_Pinkman 3361 silver badge5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

The data passed by wp_localize_script() is output in a <script> tag in the page HTML. So if you have this:

wp_localize_script( 'registered_script', 'serverData', array( 'posts' => $post_array ) );

This will be on the page:

<script type="text/javascript">
    /* <![CDATA[ */
    var serverData = { "posts": [] };
    /* ]]> */
</script>

This means that if your page HTML is cached with something like WP Super Cache or WP Rocket this data will also be cached. So if you need the data to be 100% up to date, to the second, then you should retrieve fresh data via AJAX in your script.

Keep in mind that wp_localize_script() was originally designed to provide localized/translated strings to scripts, and those don't need to be updated anywhere near that frequently.

本文标签: plugin developmentwplocalizescript and hostbrowser cache