Support » Plugin: Cache External Scripts » Cache other scripts too?

  • MariusG


    Hey @voorsie,

    Thanks for building this plugin, I’ve just tested it and it works great.
    The name is a bit confusing though because I expected more scripts than just analytics.js

    Most important for me would be other scripts from Google, such as Tag Manager or Enhanced Ecommerce, but it would be best if you could cache any external script.

    The name suggests more scripts, so I’m guessing you had planned to extend it 🙂 Hopefully that’s the case.

    Either way, it’s a great plugin, does the job.


Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Author Voorsie


    Hi Marius,

    Thanks for your message, I’m happy the to read you like the plugin.

    In fact that is exactly the case, I am planning to upgrade the plugin to be able to work for multiple scripts in the future. Unfortunately I can’t give an ETA since I’m very busy on other projects at the moment.

    Again, thanks for your kind reply. Please do leave some feedback on the plugin page as well to support the plugin.

    Kind regards,



    Hi Diego,

    Thanks for the quick reply, looking forward to see the update.
    I’ll go drop a review, this plugin needs more love 🙂


    +1 from me, too. great plugin, would be awesome if it could do google API, facebook, twitter etc.

    Thanks so much

    I have done a very quick implementation to support other js files, feel free to use it but be aware that there is no validation whatsoever here, so ensure the scripts are replaced correctly by looking at the source.

     * Plugin Name: Cache External Scripts
     * Plugin URI:
     * Description: This plugin allows you to cache the Google Analytics JavaScript file to be cached for more than 2 hours, for a better PageSpeed score
     * Version: 0.3
     * Author: Diego Voors
     * Author URI:
     * License: GPL2
    //Define uploads directory to store cached scripts
    $wp_upload_dir = wp_upload_dir();
    // create a scheduled event (if it does not exist already)
    function ces_cronstarter_activation() {
    	if( !wp_next_scheduled( 'cache-external-scripts-cron' ) ) {
    	   wp_schedule_event( time(), 'daily', 'cache-external-scripts-cron' );
    // and make sure it's called whenever WordPress loads
    add_action('wp', 'ces_cronstarter_activation');
    // unschedule event upon plugin deactivation
    function ces_cronstarter_deactivate() {
    	// find out when the last event was scheduled
    	$timestamp = wp_next_scheduled ('cache-external-scripts-cron');
    	// unschedule previous event if any
    	wp_unschedule_event ($timestamp, 'cache-external-scripts-cron');
    register_deactivation_hook (__FILE__, 'ces_cronstarter_deactivate');
    function get_data($url) {
    	$ch = curl_init();
    	$timeout = 5;
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    	$data = curl_exec($ch);
    	return $data;
    // here's the function we'd like to call with our cron job
    function function_cache_external_scripts() {
    	$dir = UPLOAD_BASE_DIR.'/cached-scripts';
    	if (!file_exists($dir) && !is_dir($dir)) {
    	$analytics_data = get_data('');
    	if($analytics_data AND (!file_exists(UPLOAD_BASE_DIR.'/cached-scripts/analytics.js') OR $analytics_data!=file_get_contents(UPLOAD_BASE_DIR.'/cached-scripts/analytics.js'))){
    		$fp = fopen(UPLOAD_BASE_DIR.'/cached-scripts/analytics.js',"wb");
    	$ga_data = get_data('');
    	if($ga_data AND (!file_exists(UPLOAD_BASE_DIR.'/cached-scripts/ga.js') OR $ga_data!=file_get_contents(UPLOAD_BASE_DIR.'/cached-scripts/ga.js'))){
    		$fp = fopen(UPLOAD_BASE_DIR.'/cached-scripts/ga.js',"wb");
    	$options_string = get_option('ces_options');
    	$options = explode("\n", $options_string['text_string']);
    	$options = array_map('trim', $options);
    	foreach ($options as $option) {
    		$url_array = explode('/', rtrim($option, '/'));
    		$filename = end($url_array);
    	    file_put_contents( UPLOAD_BASE_DIR.'/cached-scripts/'.$filename, fopen($option, 'r'));
    // hook that function onto our scheduled event:
    add_action ('cache-external-scripts-cron', 'function_cache_external_scripts');
    add_action('get_header', 'ces_ob_start');
    add_action('wp_footer', 'ces_ob_end_flush', 99999);
    function ces_ob_start() {
    function ces_ob_end_flush() {
    function ces_filter_wp_head_output($output) {
    		$output = preg_replace('#(http:|https:|)//',UPLOAD_BASE_URL.'/cached-scripts/analytics.js',$output);
    		$output = str_replace("ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';","ga.src = '".UPLOAD_BASE_URL."/cached-scripts/ga.js'",$output);
    	$options_string = get_option('ces_options');
    	$options = explode("\n", $options_string['text_string']);
    	$options = array_map('trim', $options);
    	foreach ($options as $option) {
    		$url_array = explode('/', rtrim($option, '/'));
    		$filename = end($url_array);
    		$file_dir = UPLOAD_BASE_DIR.'/cached-scripts/'.$filename;
    		$file_url = UPLOAD_BASE_URL.'/cached-scripts/'.$filename;
    			$output = str_replace($option, rtrim($file_url,'/'), $output);
      return $output;
    add_action( 'admin_menu', 'ces_add_admin_menu' );
    add_action( 'admin_init', 'ces_settings_init' );
    function ces_add_admin_menu(  ) {
    	add_options_page( 'Cache External Scripts', 'Cache External Scripts', 'manage_options', 'cache-external-scripts', 'ces_options_page' );
    function ces_settings_init(  ) {
    	register_setting( 'pluginPage', 'ces_settings', 'validate_input' );
    function ces_options_page(  ) {
    		<h1>Cache External Sources</h1>
    	if(isset($_GET['action']) && $_GET['action']=='cache-scripts'){
    		echo 'Fetching scripts...</p>';
    	if(file_exists(UPLOAD_BASE_DIR.'/cached-scripts/analytics.js') AND file_exists(UPLOAD_BASE_DIR.'/cached-scripts/ga.js')){
    		echo '<p>Google Analytics file (analytics.js) succesfully cached on local server!</p>';
    		$options_string = get_option('ces_options');
    		$options = explode("\n", $options_string['text_string']);
    		echo '<p>In case you want to force the cache to be renewed, click <a href="'.get_site_url().'/wp-admin/options-general.php?page=cache-external-scripts&action=cache-scripts">this link</a><br />';
    		echo '<span style="margin-top:70px;background-color:#fff;padding:10px;border:1px solid #C42429;display:inline-block;">Did this plugin help you to leverage browser caching and increase your PageSpeed Score? <a href="" target="_blank">Please rate the plugin</a>!<br />Did not work for your site? <a href="" target="_blank">Please let us know</a>!</span>';
    		echo '<p>Google Analytics file (analytics.js) is not cached yet on the local server. Please refresh <a href="'.get_site_url().'" target="_blank">your frontpage</a> to start the cron or start it manually by pressing <a href="'.get_site_url().'/wp-admin/options-general.php?page=cache-external-scripts&action=cache-scripts">this link</a>.</p>';
    	<form method="post" action="options.php">
    	<?php settings_fields('ces_options'); ?>
    	<?php do_settings_sections('plugin'); ?>
    	<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
    add_action('admin_init', 'plugin_admin_init');
    function plugin_admin_init(){
    	register_setting( 'ces_options', 'ces_options', 'ces_options_validate' );
    	add_settings_section('ces_main', 'Additional scripts', 'ces_section_text', 'plugin');
    	add_settings_field('ces_text_string', 'Scripts:', 'ces_setting_string', 'plugin', 'ces_main');
    function ces_section_text() {
    	echo '<p>Add the full url of any additional javascripts you want to cache below (one per line)</p>';
    function ces_setting_string() {
    	$options = get_option('ces_options');
    	echo "<textarea id='ces_text_string' name='ces_options[text_string]' rows='10' cols='50' >".$options['text_string']."</textarea>";
    function ces_options_validate($input) {
    	return $input;
Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Cache other scripts too?’ is closed to new replies.