Blog Sections Open

Delaying Slow Snippets with AjaxSnippet

How to move a heavy snippet call out of the initial page render by wrapping it in an AjaxSnippet loader with a unique request id and a lightweight preloader.

If a snippet is slow, the first job is to optimize it. But sometimes the snippet is already as lean as it can be, or the expensive part only needs to load after the page appears. In that case, deferred execution can be a clean compromise.

The idea

Create a wrapper snippet that checks for a dedicated AJAX request and only then runs the real snippet. During the initial page render, it prints a lightweight placeholder and a loader script.

Original call

[[DocLister?
    &tpl=`@CODE:[+pagetitle+]`
    ...
]]

Deferred call

[[AjaxSnippet?
    &as_id=`home-list`
    &snippet=`DocLister`
    &tpl=`@CODE:[+pagetitle+]`
    &preloader=`@CODE:Loading...`
    ...
]]

Core wrapper idea

<?php
if ((!$snippet) || (!$as_id)) {
    return;
}

if (isset($_GET['ajax']) && $_GET['ajax'] === $as_id) {
    echo $modx->runSnippet($snippet, $params);
    exit();
}

$url = ((!empty($_SERVER['HTTPS'])) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$glue = (strpos($url, '?') === false) ? '?' : '&';
$ajaxUrl = $url . $glue . 'ajax=' . urlencode($as_id);

return '<div id="ajax-snippet-' . $as_id . '">' . ($preloader ?: '') . '</div>'
    . '<script>fetch("' . $ajaxUrl . '").then(r => r.text()).then(html => document.getElementById("ajax-snippet-' . $as_id . '").innerHTML = html);</script>';

When this pattern helps

  • long lists that are not critical for first paint
  • widgets below the fold
  • expensive reporting blocks in dashboards
  • sidebars or tabs that can load after the main page shell

It is not a replacement for optimization, but it is a practical technique when you need a fast page response without removing useful dynamic output.

Newer post

Where to Configure Cache Storage in Evolution CMS

A quick guide to choosing and configuring the cache driver in Evolution CMS, including where the setting lives and when file, Redis, Memcached, or database cache makes sense.

Older post

Why GET Parameters Disappear on the Home Page

A routing and redirect troubleshooting note for projects where GET parameters are stripped only on the site home page.