Plugins and caching

@Perlkonig

Looking for an alternative to my previous solution where javascript is embedded in the cached page content.

Not sure which one is better, more efficient, or cleaner…

TLDR:

  • In GChartShortcode::process() save generated script into frontmatter of page.
  • Fetch javascript from page’s frontmatter in google-charts.php during onTwigSiteVariables event and add to assets .
  • Charts will be drawn when cache is off and on…

Longread:
Did some tests to find the event when assest can be added. onTwigSiteVariables seems to be one of the latest. And it is after onPageContentProcessed in which your process() is running.

I made the following changes to your GChartShortcode::process():

  • Removed both addAssets()
  • Added the following right after you generated the javascript into $code:
    $header->set('google-charts.test.script', $code);
    $this->grav['page']->header($header->items);
    $this->grav['page']->save();
    

And added the following function in google-charts.php:

public function onTwigSiteVariables()
{
    $header = $this->grav['page']->header();
    $header = new \Grav\Common\Page\Header((array) $header);
    $script = $header->get('google-charts.test.script');

    $this->grav['assets']->addJs('https://www.gstatic.com/charts/loader.js', ['group' => 'bottom']);
    $this->grav['assets']->addInlineJs($script, ['loading' => 'inline', 'group' => 'bottom']);
}

This way, the scripts are added in onTwigSiteVariables which is run when cache is both false and true.