functions – Advanced method to control cache of enqueued style/script


I have a WordPress website with medium-level traffic, ~10,000 unique visitors a day. Arround 30% of my daily visitors are recurrent. I constantly make some UI improvements: colors, font-size, javascript UX elements etc. Therefore on the same day, I can change .js and .css maybe 2 or 3 times. The problem is: the recurring visitors are viewing cached versions of the css/javascript files).

I’ve found this real useful script:

function my_load_scripts($hook) {
    // create my own version codes
    $my_js_ver  = date("ymd-Gis", filemtime( plugin_dir_path( __FILE__ ) . 'js/custom.js' ));
    $my_css_ver = date("ymd-Gis", filemtime( plugin_dir_path( __FILE__ ) . 'style.css' ));
    wp_enqueue_script( 'custom_js', plugins_url( 'js/custom.js', __FILE__ ), array(), $my_js_ver );
    wp_register_style( 'my_css',    plugins_url( 'style.css',    __FILE__ ), false,   $my_css_ver );
    wp_enqueue_style ( 'my_css' );
add_action('wp_enqueue_scripts', 'my_load_scripts');

This will make a versioning name based on the day the file its created, but I’m afraid to put it in public, because it will run everytime a user visit the website. And I’m afraid that the server can run out of resources.

Do you have another method?

Alexandro Giles 1 month 2021-10-22T14:31:32-05:00 0 Answers 0 views 0

Leave an answer