Commit df9e3fe4 authored by jan.koester's avatar jan.koester
Browse files

theme: add defer to script tags, optimize DOM walker for TBT reduction

parent 9e37bf55
Loading
Loading
Loading
Loading
+23 −5
Changes for src/theme.cpp: 23 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -504,13 +504,19 @@ void blogi::Theme::printSite(const int tid,libhtmlpp::HtmlString &output,libhtml
        injectThemeColors(tid, index);

        // Add loading="lazy" to all <img> tags except the banner logo (above the fold)
        // Add "defer" to inline <script> tags to reduce TBT
        // Merge per-widget <style> blocks into one consolidated block to reduce CSSOM recalculations
        {
            std::function<void(libhtmlpp::Element*)> addLazyImages = [&](libhtmlpp::Element *node) {
            libhtmlpp::HtmlString mergedCSS;
            bool hasMergedCSS = false;

            std::function<void(libhtmlpp::Element*)> optimizeDOM = [&](libhtmlpp::Element *node) {
                if (!node) return;
                if (node->getType() == libhtmlpp::HtmlEl) {
                    libhtmlpp::HtmlElement *hel = static_cast<libhtmlpp::HtmlElement*>(node);
                    if (hel->getTagname() == "img") {
                        // Check if this is the banner logo (skip — above the fold)
                    const std::string &tag = hel->getTagname();

                    if (tag == "img") {
                        bool isBanner = false;
                        bool hasLoading = false;
                        for (auto *attr = hel->firstAttribute(); attr; attr = attr->nextAttribute()) {
@@ -522,11 +528,23 @@ void blogi::Theme::printSite(const int tid,libhtmlpp::HtmlString &output,libhtml
                        if (!isBanner && !hasLoading)
                            hel->setAttribute("loading", "lazy");
                    }

                    for (auto *child = hel->firstChild(); child; child = child->nextElement())
                        addLazyImages(child);
                        optimizeDOM(child);
                } else if (node->getType() == libhtmlpp::ScriptEL) {
                    // Add defer to script elements to avoid blocking the main thread
                    libhtmlpp::ScriptElement *sel = static_cast<libhtmlpp::ScriptElement*>(node);
                    bool hasDefer = false;
                    bool hasAsync = false;
                    for (auto *attr = sel->firstAttribute(); attr; attr = attr->nextAttribute()) {
                        if (attr->getKey() == "defer") hasDefer = true;
                        if (attr->getKey() == "async") hasAsync = true;
                    }
                    if (!hasDefer && !hasAsync)
                        sel->setAttribute("defer", "");
                }
            };
            addLazyImages(index);
            optimizeDOM(index);
        }

        // Print the final HTML structure to the output stream