Can’t change boolean from inside of .onError in JS [duplicate]

I can’t seem to switch the boolean value of ‘errorcheck’ using image .onerror function.
I’m able to see console logs, trigger functions from inside the .onerror but I just can’t change the variable ‘errorcheck’

The goal is to have a for loop that adds item icons until a broken image path is found

let errorcheck= false;

document.addEventListener('DOMContentLoaded', function() {
  const itemInventory = document.getElementById('itembox');
  const totalItems= 25; //+1 actual count
  let inventoryadd="";
  
  for(let i = 1; i < totalItems; i++) {
    if (errorcheck) {
      break;
    }

    const itemImg= new Image();
    itemImg.src = `images/itemicon${i}.png`;

    // This isn't working
    itemImg.onerror = () => {
      errorcheck= true;
    }

    // returns errorcheck= false;
    console.log(errorcheck);

    inventoryadd += 
    `<li class="itemIcons">
    <img id="itemicon${i}" class="icons" onclick="itemCLick(this.id)" src="images/itemicon${i}.png">
    </li>`;

    myImage.remove();


    }
 
 
  itemInventory.innerHTML += inventoryadd;
    
});

Is there a way to extract the header HTML tag from a given URL dinamically with php?

I have a WordPress website, and I need to extract into a PHP plugin the header tag from this website, and format the code like this:

<style>
    Code stylization grouped if needed on the header here
</style>
<header>
    Header extracted from WordPress
</header>
<script>
    Scripts grouped if needed on the header here
</script>

I already did something interesting, but I’m having trouble loading two dropdown lists with options from the html (HOTELS and LANG).

Here is a sample HTML code from a random page:

<header class="fusion-header-wrapper">
    <div class="fusion-header-v5 fusion-logo-alignment fusion-logo-center fusion-sticky-menu- fusion-sticky-logo- fusion-mobile-logo- fusion-sticky-menu-only fusion-header-menu-align-center fusion-mobile-menu-design-modern">
        <div class="fusion-secondary-header">
            <div class="fusion-row">
                <div class="fusion-alignleft">
                    <div class="fusion-contact-info">
                        <span class="fusion-contact-info-phone-number">(+351) 300 528 059</span>
                        <span class="fusion-header-separator">|</span>
                        <span class="fusion-contact-info-email-address">
                            <a href="mailto:&#114;e&#115;&#101;r&#118;as&#64;tu&#114;&#105;mho&#116;e&#105;&#115;.c&#111;&#109;">&#114;e &#115;&#101;r &#118;as &#64;tu &#114;&#105;mho &#116;e &#105;&#115;.c &#111;&#109;</a>
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="fusion-header-sticky-height"></div>
        <div class="fusion-sticky-header-wrapper">
            <!-- start fusion sticky header wrapper -->
            <div class="fusion-header">
                <div class="fusion-row">
                    <div class="fusion-logo" data-margin-top="31px" data-margin-bottom="31px" data-margin-left="0px" data-margin-right="0px">
                        <a class="fusion-logo-link" href="https://my-site.com/">
                            <!-- standard logo -->
                            <img src="https://my-site.com/Logo.png" srcset="https://my-site.com/Logo.png 1x" width="308" height="105" alt="Book your stay on the Hotels official website! Logo" data-retina_logo_url="" class="fusion-standard-logo"/>
                        </a>
                    </div>
                    <div class="fusion-mobile-menu-icons">
                        <a href="#" class="fusion-icon awb-icon-bars" aria-label="Toggle mobile menu" aria-expanded="false"></a>
                    </div>
                </div>
            </div>
            <div class="fusion-secondary-main-menu">
                <div class="fusion-row">
                    <nav class="fusion-main-menu" aria-label="Main Menu">
                        <div class="fusion-overlay-search">
                            <form role="search" class="searchform fusion-search-form  fusion-search-form-clean" method="get" action="https://my-site.com">
                                <div class="fusion-search-form-content">
                                    <div class="fusion-search-field search-field">
                                        <label>
                                            <span class="screen-reader-text">Search for:</span>
                                            <input type="search" value="" name="s" class="s" placeholder="Search..." required aria-required="true" aria-label="Search..."/>
                                        </label>
                                    </div>
                                    <div class="fusion-search-button search-button">
                                        <input type="submit" class="fusion-search-submit searchsubmit" aria-label="Search" value="&#xf002;"/>
                                    </div>
                                </div>
                            </form>
                            <div class="fusion-search-spacer"></div>
                            <a href="#" role="button" aria-label="Close Search" class="fusion-close-search"></a>
                        </div>
                        <ul id="menu-main-menu" class="fusion-menu">
                            <li id="menu-item-3946" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-3946 fusion-dropdown-menu" data-item-id="3946">
                                <a href="#" class="fusion-bottombar-highlight">
                                    <span class="menu-text">HOTELS</span>
                                    <span class="fusion-caret">
                                        <i class="fusion-dropdown-indicator" aria-hidden="true"></i>
                                    </span>
                                </a>
                                <ul class="sub-menu">
                                    <li id="menu-item-3947" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-3947 fusion-dropdown-submenu">
                                        <a href="#" class="fusion-bottombar-highlight">
                                            <span>HOTEL-01</span>
                                            <span class="fusion-caret">
                                                <i class="fusion-dropdown-indicator" aria-hidden="true"></i>
                                            </span>
                                        </a>
                                        <ul class="sub-menu">
                                            <li id="menu-item-4037" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4037">
                                                <a href="https://my-site.com/hotel01" class="fusion-bottombar-highlight">
                                                    <span>hotel01</span>
                                                </a>
                                            </li>
                                            <li id="menu-item-4035" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4035">
                                                <a href="https://my-site.com/hotel02" class="fusion-bottombar-highlight">
                                                    <span>hotel02</span>
                                                </a>
                                            </li>
                                            <li id="menu-item-4782" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4782">
                                                <a href="https://my-site.com/hotel03" class="fusion-bottombar-highlight fusion-has-highlight-label">
                                                    <span>hotel03</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                    <li id="menu-item-3962" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-3962 fusion-dropdown-submenu">
                                        <a href="#" class="fusion-bottombar-highlight">
                                            <span>HOTEL-02</span>
                                            <span class="fusion-caret">
                                                <i class="fusion-dropdown-indicator" aria-hidden="true"></i>
                                            </span>
                                        </a>
                                        <ul class="sub-menu">
                                            <li id="menu-item-4031" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4031">
                                                <a href="https://my-site.com/hotel01" class="fusion-bottombar-highlight">
                                                    <span>hotel01</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                </ul>
                            </li>
                            <li id="menu-item-26285" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-26285" data-item-id="26285">
                                <a href="https://bookings.turim-hotels.com/pt/bookcore/loyalty/account" class="fusion-bottombar-highlight">
                                    <span class="menu-text">CLUB</span>
                                </a>
                            </li>
                            <li id="menu-item-6094" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6094" data-item-id="6094">
                                <a href="https://turim-hotels.com/en/events-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">EVENTS</span>
                                </a>
                            </li>
                            <li id="menu-item-6095" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6095" data-item-id="6095">
                                <a href="https://turim-hotels.com/en/corporate-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">CORPORATE</span>
                                </a>
                            </li>
                            <li id="menu-item-19578" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-19578" data-item-id="19578">
                                <a href="https://turim-hotels.com/en/trade/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">TRADE</span>
                                </a>
                            </li>
                            <li id="menu-item-6093" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6093" data-item-id="6093">
                                <a href="https://turim-hotels.com/en/news-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">NEWS</span>
                                </a>
                            </li>
                            <li id="menu-item-6092" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6092" data-item-id="6092">
                                <a href="https://turim-hotels.com/en/promotions-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">PROMOTIONS</span>
                                </a>
                            </li>
                            <li id="menu-item-6091" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6091" data-item-id="6091">
                                <a href="https://turim-hotels.com/en/careers-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">CAREERS</span>
                                </a>
                            </li>
                            <li id="menu-item-6096" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6096" data-item-id="6096">
                                <a href="https://turim-hotels.com/en/contacts-en/" class="fusion-bottombar-highlight">
                                    <span class="menu-text">CONTACTS</span>
                                </a>
                            </li>
                            <li id="menu-item-3987" class="pll-parent-menu-item menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-3987 fusion-dropdown-menu" data-classes="pll-parent-menu-item" data-item-id="3987">
                                <a href="#pll_switcher" class="fusion-bottombar-highlight">
                                    <span class="menu-text">
                                        <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAMAAABBPP0LAAAAt1BMVEWSmb66z+18msdig8La3u+tYX9IaLc7W7BagbmcUW+kqMr/q6n+//+hsNv/lIr/jIGMnNLJyOP9/fyQttT/wb3/////aWn+YWF5kNT0oqz0i4ueqtIZNJjhvt/8gn//WVr/6+rN1+o9RKZwgcMPJpX/VFT9UEn+RUX8Ozv2Ly+FGzdYZrfU1e/8LS/lQkG/mbVUX60AE231hHtcdMb0mp3qYFTFwNu3w9prcqSURGNDaaIUMX5FNW5wYt7AAAAAjklEQVR4AR3HNUJEMQCGwf+L8RR36ajR+1+CEuvRdd8kK9MNAiRQNgJmVDAt1yM6kSzYVJUsPNssAk5N7ZFKjVNFAY4co6TAOI+kyQm+LFUEBEKKzuWUNB7rSH/rSnvOulOGk+QlXTBqMIrfYX4tSe2nP3iRa/KNK7uTmWJ5a9+erZ3d+18od4ytiZdvZyuKWy8o3UpTVAAAAABJRU5ErkJggg==" alt="" width="16" height="11" style="width: 16px; height: 11px;"/>
                                        <span style="margin-left:0.3em;">English</span>
                                    </span>
                                    <span class="fusion-caret">
                                        <i class="fusion-dropdown-indicator" aria-hidden="true"></i>
                                    </span>
                                </a>
                                <ul class="sub-menu">
                                    <li id="menu-item-3987-pt" class="lang-item lang-item-15 lang-item-pt lang-item-first menu-item menu-item-type-custom menu-item-object-custom menu-item-3987-pt fusion-dropdown-submenu" data-classes="lang-item">
                                        <a href="https://my-site.com/" class="fusion-bottombar-highlight" hreflang="pt-PT" lang="pt-PT">
                                            <span>
                                                <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAABL0lEQVR4AV2RA2yEQRCFNxcnRVw3qG3bthXUbZxaUaOGRVA7ro2wDWoEtW2b9/b2nHx3v943uztDSAwhAQJ86P83keCJw2HcEAJoqLivmJHbnQt+s7OFfMXHMz5DAgBPCKBCUktSRmdK43Dw3Gz451TIc68nPr+7uLzZWr2Zm78bGLxpa797e1+IC0erUeAmL+ol3R8CEE+/qqvDv2BbwjYi6yJR+6Ys5m5zA0C7HbWEIEy/KCpKC8uzQRf5fkivX3zBZIIw/Swvj8cTKthRIbDGDwcYnXRF7avy/KM5q8NZg2cDPWEaYHt8AceFACBsTdui9nmn8VWmpngawN+ngiEVHCocGM5Vpu8G0rUB5iAS0CKAYwCsg/YB1lPWKESBSCAqhMiKwHQueJwI2BeDC83C2lDIxUCuAAAAAElFTkSuQmCC" alt="" width="16" height="11" style="width: 16px; height: 11px;"/>
                                                <span style="margin-left:0.3em;">Português</span>
                                            </span>
                                        </a>
                                    </li>
                                    <li id="menu-item-3987-es" class="lang-item lang-item-445 lang-item-es menu-item menu-item-type-custom menu-item-object-custom menu-item-3987-es fusion-dropdown-submenu" data-classes="lang-item">
                                        <a href="https://my-site.com/es" class="fusion-bottombar-highlight" hreflang="es-ES" lang="es-ES">
                                            <span>
                                                <img loading="lazy" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAMAAABBPP0LAAAAflBMVEX/AAD9AAD3AADxAADrAAD/eXn9bGz8YWH8WVn6UVH5SEj5Pz/3NDT0Kir9/QD+/nL+/lT18lDt4Uf6+j/39zD39yf19R3n5wDxflXsZ1Pt4Y3x8zr0wbLs1NXz8xPj4wD37t3jmkvsUU/Bz6nrykm3vJ72IiL0FBTyDAvhAABEt4UZAAAAX0lEQVR4AQXBQUrFQBBAwXqTDkYE94Jb73+qfwVRcYxVQRBRToiUfoaVpGTrtdS9SO0Z9FR9lVy/g5c99+dKl30N5uxPuviexXEc9/msC7TOkd4kHu/Dlh4itCJ8AP4B0w4Qwmm7CFQAAAAASUVORK5CYII=" alt="" width="16" height="11" style="width: 16px; height: 11px;"/>
                                                <span style="margin-left:0.3em;">Español</span>
                                            </span>
                                        </a>
                                    </li>
                                </ul>
                            </li>
                        </ul>
                    </nav>
                    <nav class="fusion-mobile-nav-holder fusion-mobile-menu-text-align-left fusion-mobile-menu-indicator-hide" aria-label="Main Menu Mobile"></nav>
                </div>
            </div>
        </div>
        <!-- end fusion sticky header wrapper -->
    </div>
    <div class="fusion-clearfix"></div>
</header>

And my plugin so far:

<?php
add_action('rest_api_init', function () {
    register_rest_route('plugin/v1', '/json', [
        'methods' => 'GET',
        'callback' => 'page_json',
        'permission_callback' => '__return_true',
        'args' => [
            'lang' => [
                'sanitize_callback' => 'sanitize_text_field',
                'default' => 'pt',
            ],
        ],
    ]);
});

function get_lang_url($lang) {
    $urls = array(
        'pt' => 'ptUrlPlaceholder',
        'en' => 'enUrlPlaceholder',
        'es' => 'esUrlPlaceholder'
    );
    return $urls[$lang];
}

function resolve_url($base, $relative) {
    if (parse_url($relative, PHP_URL_SCHEME)) return $relative;
    $base = rtrim($base, '/');
    return $base . '/' . ltrim($relative, '/');
}

function css_fix_urls($css, $baseUrl) {
    return preg_replace_callback(
        '/url((["']?)(?!data:|https?:|//)([^"')]+)1)/i',
        function($m) use ($baseUrl) {
            $path = resolve_url($baseUrl, $m[2]);
            return "url('{$path}')";
        },
        $css
    );
}

function get_clean_dom($url) {
    $response = wp_remote_get($url);
    if (is_wp_error($response)) {
        return new WP_Error('fetch_error', 'Erro ao acessar o site externo', ['status' => 500]);
    }

    $html = wp_remote_retrieve_body($response);
    if (empty($html)) {
        return new WP_Error('empty_html', 'Conteúdo vazio recebido do site externo', ['status' => 500]);
    }

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    return $dom;
}

function inject_style($dom, $headerNode, $styleBlock) {
    if (!$headerNode) return;
    if ($styleBlock) {
        $frag = $dom->createDocumentFragment();
        $frag->appendXML($styleBlock);
        $headerNode->insertBefore($frag, $headerNode->firstChild);
    }
}

function remove_links_and_scripts($dom, $node) {
    $xpath = new DOMXPath($dom);
    foreach ($xpath->query('.//link[@rel="stylesheet"]', $node) as $ln) { $ln->parentNode->removeChild($ln); }
    foreach ($xpath->query('.//script', $node) as $s) {
        $s->parentNode->removeChild($s);
    }
}

function collect_and_inline_css_simple($dom, $baseUrl) {
    $xpath = new DOMXPath($dom);
    $cssParts = [];

    foreach ($xpath->query('//style') as $styleNode) {
        $cssParts[] = $styleNode->nodeValue;
    }

    foreach ($xpath->query('//link[@rel="stylesheet"]') as $linkNode) {
        $href = $linkNode->getAttribute('href');
        if (!$href) continue;
        $full = resolve_url($baseUrl, $href);
        $res = wp_remote_get($full, ['timeout'=>15]);
        if (!is_wp_error($res)) {
            $css = wp_remote_retrieve_body($res);
            $css = css_fix_urls($css, $full);
            $cssParts[] = $css;
        }
    }

    $all = implode("n", $cssParts);
    return $all ? "<style>n{$all}n</style>" : '';
}

function collect_needed_scripts($url, $xpath) {
    $scriptContent = [];

    foreach ($xpath->query('//script[@src]') as $s) {
        $src = $s->getAttribute('src');
        if (!$src) continue;
        $full = resolve_url($url, $src);

        if (strpos($full, 'jquery') !== false ||
            strpos($full, 'avada') !== false ||
            strpos($full, 'fusion') !== false) {

            $res = wp_remote_get($full, ['timeout'=>15]);
            if (!is_wp_error($res)) {
                $code = wp_remote_retrieve_body($res);
                if ($code) {
                    $scriptContent[] = "n/* Script: {$full} */n" . $code;
                }
            }
        }
    }

    foreach ($xpath->query('//script[not(@src)]') as $s) {
        $code = trim($s->nodeValue);
        if ($code) {
            $scriptContent[] = "n/* Inline Script */n" . $code;
        }
    }

    $all = implode("n", $scriptContent);
    return $all ? "<script>n{$all}n</script>" : '';
}

function page_json($request) {
    $lang = $request->get_param('lang');
    $url  = get_lang_url($lang);

    $dom = get_clean_dom($url);
    if (is_wp_error($dom)) {
        return ['error' => 'DOM error'];
    }

    $xpath = new DOMXPath($dom);
    $headerNode = $xpath->query('//header')->item(0);
    $footerNode = $xpath->query('//footer')->item(0);

    $styleBlock = collect_and_inline_css_simple($dom, $url);

    $allScripts = collect_needed_scripts($url, $xpath);

    if ($headerNode) remove_links_and_scripts($dom, $headerNode);
    if ($footerNode) remove_links_and_scripts($dom, $footerNode);

    $headerHtml = $headerNode ? $dom->saveHTML($headerNode) : '';
    $footerHtml = $footerNode ? $dom->saveHTML($footerNode) : '';

    $finalHeader = $styleBlock . "n" . $headerHtml . "n" . $allScripts;

    return [
        'header' => $finalHeader,
        'footer' => $footerHtml
    ];
}

What am I doing wrong here?

Listener for opening a section in Elementor edit panel

I want some elements in my widget to be hidden when a specific section in the Style tab is opened in Elementor.

For example, I have this section (currently empty):

$this->end_controls_section();

$this->start_controls_section('section_style_counter', [
 'label' => 'Счетчик',
 'tab'   => Controls_Manager::TAB_STYLE,
]);

$this->add_control('counter_btns', [
 'label' => 'Кнопки счетчика',
 'type'  => Controls_Manager::HEADING,
]);

How can I add a listener to detect when this section is opened?
Basically, I want to run some JS code only when this section is expanded in the Elementor panel.

I tried adding an event listener in JS on click for the section, but it seems to ignore it.

MongoDB query with Mongoose – Matching subdocument attribute within an array

I am trying to solve an issue with the format of documents in a MongoDB depicted below.

{
  "_id": {
    "$oid": "68dc4f78e11553b3647231e2"
  },
  "name": "Dutch Bros",
  "address": "25 Down Street, Salt Lake City, UT",
  "facilities": [
    "Hot drinks",
    "Food"
  ],
  "coords": [
    -0.9690884,
    51.455041
  ],
  "reviews": [
    {
      "author": "John Smith",
      "rating": {
        "$numberDecimal": "5"
      },
      "createdOn": {
        "$date": "2025-09-30T06:00:00.000Z"
      },
      "reviewText": "Great Place. Would come back again!"
    },
    {
      "author": "Jane Doe",
      "rating": {
        "$numberDecimal": "4"
      },
      "createdOn": {
        "$date": "2025-09-30T06:00:00.000Z"
      },
      "reviewText": "Okay Place. Would come back again!"
    }
  ]
}

My goal is to match review sub-document(s) based on an attribute it has such as ratings being equal to five. I know that I could take the reviews array as a whole and iterate over them to search the attributes for what I need, but I want to be able to find it directly in the MongoDB query so the MongoDB server does the work while it saves my express server any additional workload.

I guess what I am asking is how do I reference the iterable objects in the reviews array. I hope that was clear enough and I apologize if it wasn’t!

I’ve successfully implemented a version that iterates in a for loop on the express server in the controller, but this is what I want to avoid. I’ve also tried using a .get() method on the returned array because I saw that it was an available method for the object, but that yielded an error. I’ve also tried to build a query which was close to what I believe the solution is going to be but I can’t understand how MongoDB element matches an array item, see below for my failed attempt.

const monReview = await Loc
            .findById(req.params.locationid)
            .select('name reviews')
            .where('reviews')
            .elemMatch({$eq: req.params.reviewRating})
            .exec();  

Update total in Stripe payments upon shipping rate change (Amazon, Google Pay etc)

Here is some infromation about shippingratechange for Stripe express checkout.
https://docs.stripe.com/js/elements_object/express_checkout_element_shippingratechange_event

which implemented and when the Stripe payment button is clicked the modal window properly displayed:
enter image description here

Then, as you see on the image, there are several shipping options properly passed and rendered. Once another shipping option (with another price) is chosen, it triggers ‘shippingratechange’. How to update the Total because the shipping price was changed?

When I change the shipping option, it changes fine, but the Total remains unchanged, although shippingratechange gets triggered with no questions. How to set another totals value, for example 99.90 (let’s say the math calculated).

What should be added to here?

expressCheckoutElement.on('shippingratechange', function(event) {
  var resolve = event.resolve;
  var shippingRate = event.shippingRate;
  // handle shippingratechange event

  // define payload and pass it into resolve
  var payload = {
    shippingRates: [
      shippingRate
    ]
  };

  // call event.resolve within 20 seconds
  resolve(payload);
});

Why does a small React dynamic import file (~3.7 KB) take 650 ms on first load but only 45 ms on refresh with AWS S3 + CloudFront?

I have a React app deployed on AWS S3 + CloudFront.

One of my routes uses a dynamic import (import()), and the corresponding JS chunk is very small (~3.7 KB).

On the first load, the request for this file takes about 650 ms, but if I refresh the page immediately afterward, it only takes about 45 ms.

Here’s the request and response details from Chrome DevTools for the file:

Request URL: https://admin.simprosysapis.com/assets/RolesList-DVgRFD0k.js
Request Method: GET
Status Code: 200 OK
Remote Address: 18.66.57.77:443
Referrer Policy: strict-origin-when-cross-origin

Response headers

cache-control: max-age=3600, must-revalidate
content-encoding: br
content-type: text/javascript
server: SimprosysAPI
via: 1.1 ...cloudfront.net (CloudFront)
x-cache: Miss from cloudfront

Request headers

accept-encoding: gzip, deflate, br, zstd
cache-control: no-cache
pragma: no-cache
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ...

My questions

  1. Why does a 3.7 KB file take ~650 ms to load the first time?

    • Is this mostly TLS/handshake + CloudFront latency rather than file size?
    • Is the x-cache: Miss from cloudfront header responsible?
  2. Why does it become so much faster (~45 ms) on refresh?

    • Is the browser using disk/memory cache or a CloudFront cached copy?
  3. Is there a way to improve the first load time for these small dynamic chunks (e.g., preloading, prefetching, or CloudFront settings)?


What I tried

  • Checked headers: content-encoding: br confirms compression is working.
  • Cache headers look reasonable (max-age=3600).
  • Behavior is consistent across multiple builds.

Expected / Desired

I want to understand if this latency difference is normal for CloudFront + S3 dynamic imports, and whether I can optimize the first-load latency further.

How to achieve an “inset carved” gallery card effect inside an image container with CSS clip-path or masks? [closed]

Reference
my trial

I’m trying to replicate a hero section design where the gallery card looks like it is carved into the main image container (instead of floating on top).

I attempted using an SVG clipPath with an organic shape applied to the .main-image, but the gallery card still appears as a separate overlay. It doesn’t blend with the container as expected.

<div class="organic-gallery">
  <!-- Clip path definition -->
  <svg width="0" height="0">
    <defs>
      <clipPath id="organic-carved-shape" clipPathUnits="objectBoundingBox">
        <path d="M 0.06,0 L 0.94,0 C 0.97,0 1,0.03 1,0.06 L 1,0.94 C 1,0.97 0.97,1 0.94,1 L 0.7,1 C 0.68,1 0.66,0.998 0.64,0.995 L 0.05,0.82 C 0.02,0.815 0,0.8 0,0.78 L 0,0.06 C 0,0.03 0.03,0 0.06,0 Z" />
      </clipPath>
    </defs>
  </svg>

  <div class="gallery-container">
    <!-- Main image background -->
    <div class="main-image">
      <img src="circuit.jpg" class="circuit-bg" />
      
      <!-- floating labels -->
      <div class="feature-label" style="top: 3rem; right: 3rem;">On-Device Analysis</div>
      <div class="feature-label" style="top: 8rem; right: 6rem;">Smart App</div>
    </div>

    <!-- supposed to be carved into the main container -->
    <div class="gallery-card">
      <div class="gallery-images">
        <div class="gallery-item">Thumb 1</div>
        <div class="gallery-item">Thumb 2</div>
      </div>
    </div>
  </div>
</div>
.gallery-container {
  position: relative;
  height: 600px;
}

.main-image {
  position: absolute;
  inset: 0;
  border-radius: 3rem;
  overflow: hidden;
  clip-path: url(#organic-carved-shape);
}

.circuit-bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.gallery-card {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 380px;
  padding: 1.5rem;
  border-radius: 2rem;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(12px);
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}

Current result:
The gallery card simply overlaps the main image.

Expected result:
The gallery card should appear as if it’s part of (or cut into) the main container — following the same organic shape, not just sitting on top.

Question:
What’s the correct way (CSS clip-path, mask, pseudo-elements, or another technique) to make the gallery card look “carved into” the image container?

HTML Canvas lineTo() draws with incorrect y coordinates

Achieving clear lines in HTML canvas requires setting the CSS canvas height and width to be the canvas height and width / device pixel ratio:

this.element.style.height = this.element.height / dpr + "px";
this.element.style.height = this.element.height / dpr + "px";

An unfortunate outcome of this is that the lineTo command will now be incorrect. For example, if I draw a square as:

ctx.lineTo(113.395,54.233);
ctx.lineTo(120.791,54.233);
ctx.stroke();

ctx.lineTo(120.791,54.233);
ctx.lineTo(120.791,46.837);
ctx.stroke();

ctx.lineTo(120.791,46.837);
ctx.lineTo(113.395,46.837);
ctx.stroke();

ctx.lineTo(113.395,46.837);
ctx.lineTo(113.395,54.233);
ctx.stroke();

The result is not square:

enter image description here

Anti-aliasing aside, if we average the placement of each line to its darker side, the width is approximately 7px (correct), while the height is approximately 8px (incorrect).

Does anyone have a solution for this?

What will happen if Node.js cannot read a directory (or a part of a file) due to bad/problematic sectors on disk or corrupted file system?

I want to use the directory- and file-reading functions from 'node:fs' to merge multiple files into one file. For example, I have the following script:

import fs from 'node:fs';
import { readdir, readFile, stat } from 'node:fs/promises';
import { join } from 'node:path';
var myStream = fs.createWriteStream('path/to/output.txt', {flags: 'a'});
var dirPath = 'path/to/mydirectory';
try {
    const entries = await readdir(dirPath, { recursive: true, withFileTypes: true });
    for (const entry of entries) {
        if (entry.isFile()) {
        const myPath = join(entry.parentPath, entry.name);
        const { size } = await stat(myPath);
        const contents = await readFile(myPath);
        myStream.write('<path>' + myPath + '</path>' + '<size>' + size.toString(10) + '</size>n' + contents + 'n');
     }
};
} catch (err) {
    console.error(err);
}; 
myStream.end()

My question is: what will happen if a directory cannot be opened or some part of a file cannot be read (due to bad/problematic sectors on disk, corrupted file system, etc.)? Will the program just freeze, so I will need to terminate it manually? Or only the corresponding file/directory will be skipped? Will the program skip a file in its entirety or only the unreadable part of it? What type of error, if any, will the program report? I have not found any information on this topic. Would it be possible to use Node.js to make the full list of problematic directories and files that are located in a given directory?

How to persist uploaded photos in a multi-step React form across page refresh?

I’m building a multi-step form in React where users can upload photos along with other inputs.

Currently:

I store all the form values in a formData state object.

To persist progress across refreshes, I save formData in localStorage.

Problem:

Uploaded photos are stored using URL.createObjectURL(file).

These object URLs don’t survive a page refresh, so the images are lost even though the rest of the form data is restored from localStorage.

Question:

Is there a way to persist uploaded photos across page refreshes without just dumping everything into localStorage?

What are the common patterns for handling this in React multi-step forms?

Should I use IndexedDB for files?

Should I upload files immediately to a temporary backend storage (and store only the reference in localStorage)?

Or is there another best practice for this use case?

Render Issues within animated PNG inside a SVG

I saw this tutorial that teaches how to do complex multilayer parallax scrolls and implemented on my website. While prototyping I found some weird lines that would appear while manipulating the PNG’s (I know the file size is big, I will fix it later). I thought it could be just some white pixels that just needed to be cleaned, but after cleaning all edges the problem persisted. Any idea why browsers are with this render issue?

https://codepen.io/Ramoses-Hofmeister-Ferreira/pen/wBMWBvZ

I was trying to manipulate some images inside an SVG so I could have a responsive multilayer parallax scroll, yet browsers are rendering strange white lines on the edge of the PNG’s that are inside of the SVG.

HTML:

<body>
    <div class="banner">
        <div id="mountain"></div>
    </div>
</body>

CSS:

body {
    margin: 0;
    background-color: #000000;
}

#mountain {
    width: 100%;
    height: 100vh;
    overflow: hidden;
}

#mountain svg {
    width: 100%;
    height: 100%;
    object-position: center;
}

JS:

function loadSVG() {
    fetch("https://raw.githubusercontent.com/astronaut954/pedro/main/img/parallax_scroll.svg")
        .then(res => res.text())
        .then(svg => {
            const mountain = document.getElementById("mountain");
            mountain.innerHTML = svg;

            const svgEl = mountain.querySelector("svg");
            svgEl.setAttribute("preserveAspectRatio", "xMidYMid slice");

            createWrapper("#layer_1");
            createWrapper("#layer_2");

            setAnimationScroll();
            setCloudAnimation();

        });
}

function createWrapper(layerId) {
    const layer = document.querySelector(`#mountain svg ${layerId}`);
    if (!layer) return;

    const wrapper = document.createElementNS("http://www.w3.org/2000/svg", "g");
    wrapper.setAttribute("id", `${layerId.slice(1)}_wrapper`);

    layer.parentNode.insertBefore(wrapper, layer);
    wrapper.appendChild(layer);
}


loadSVG();

function setAnimationScroll() {
    gsap.registerPlugin(ScrollTrigger);

    let runAnimation = gsap.timeline({
        scrollTrigger: {
            trigger: ".banner",
            start: "top top",
            end: "+=1000",
            scrub: true,
            pin: true
        }
    });

    runAnimation.add([
        gsap.to("#cloud10_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud9_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud8_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud7_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud6_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud5_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud4_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud3_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud2_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud1_fixed", { y: -1500, duration: 2 }),
        gsap.to("#cloud2b", { y: -1500, duration: 2 }),
        gsap.to("#cloud1b", { y: -1500, duration: 2 }),
        gsap.to("#cloud10", { y: -1500, duration: 2 }),
        gsap.to("#cloud9", { y: -1500, duration: 2 }),
        gsap.to("#cloud8", { y: -1500, duration: 2 }),
        gsap.to("#cloud7", { y: -1500, duration: 2 }),
        gsap.to("#cloud6", { y: -1500, duration: 2 }),
        gsap.to("#cloud5", { y: -1500, duration: 2 }),
        gsap.to("#cloud4", { y: -1500, duration: 2 }),
        gsap.to("#cloud3", { y: -1500, duration: 2 }),
        gsap.to("#cloud2", { y: -1500, duration: 2 }),
        gsap.to("#cloud1", { y: -1500, duration: 2 })
    ])
    .add([
        gsap.to("#layer_1", {
            scale: 1.4,
            x: -250,
            y: 0,
            transformOrigin: "50% 0%",
            duration: 2
        }),
        gsap.to("#layer_2", {
            scale: 1.2,
            transformOrigin: "50% 0%",
            duration: 2
        })
    ]);
}

How can I detect when the AG Grid filter dialog closes?

I have an AG Grid, implemented in React/Typescript. It automatically updates with new data, and the columns have filters. When new data comes in, the grid reloads with the changes, which closes the filter dialog if it’s open. That’s not ideal. It seems like a viable solution would be to track when the dialog is open, and hold off on updates while it’s open. I can track when the filter dialog opens (onFilterOpened), or when it changes (onFilterChanged), but I’m not certain how to detect closing the dialog without making a change by clicking off of it so that I can resume changes.

Here’s the event code (which is basically just console logs right now) based on what an AI model suggested:

const onFilterOpened = () => {
  console.log("Filter opened.");
  setIsFilterDialogOpen(true);
};

const onSortChanged = () => {
  if (gridApiRef.current) {
    columnState.current = gridApiRef.current.getColumnState();
  }
};

const onFilterChanged = (event: { api: GridApi; }) => {
  if (
    event.api.getFilterModel() &&
    Object.keys(event.api.getFilterModel()).length > 0
  ) {
    console.log("Filter dialog is opened");
    setIsFilterDialogOpen(true);
  } else {
    console.log("Filter closed.");
    setIsFilterDialogOpen(false);
  }

  console.log("Filter changed");
};

And set up here:

<AgGridReact  
  className={"ag-theme-astro"}  
  columnDefs={colDefGrouped}  
  defaultColDef={defaultColDef}  
  rowData={groupedRowData}  
  domLayout="autoHeight"  
  pagination={true}  
  paginationPageSize={20}  
  isFullWidthRow={isFullWidthRow}  
  fullWidthCellRenderer={fullWidthCellRenderer}  
  getRowHeight={getRowHeight}  
  onGridReady={onGridReady}  
  onFilterChanged={onFilterChanged}
  onFilterOpened={onFilterOpened}
  data-testid="groupedGrid"
/>

I get the “Filter opened” message when it opens, and “Filter dialog is opened” as I type in changes in the filter. But nothing when it closes.

unable to get a hard-coded svg line on d3 chart

I’m trying to just get a simple line on a D3 chart without using an array of data (that will be the next step).

The x-axis is years from 2007 to 2023. The y-axis is numbers from 0.00 to 0.50.

I assume the data pairs I’ll need will be x in a time formatted year and y as a number.

But when I put in the code to draw a line from one point to the other on the chart, nothing appears and I get no error message.

<div id="container"></div>
<script type="module">

const width = 1140;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 50;
const marginLeft = 70;

//x-axis is years
const x = d3.scaleUtc()
    .domain([new Date("2007-01-01"), new Date("2023-01-01")])
    .range([marginLeft, width - marginRight]);

//y-axis is numbers between 0 and .5
const y = d3.scaleLinear()
    .domain([0, .5])
    .range([height - marginBottom, marginTop]);

const svg = d3.create("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x)
        .ticks(d3.utcYear.every(1))
);
    
svg.append("text") //label
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height - 6)
    .text("Year");

svg.append("text") //label
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("x", -height/3)
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("Percent");

svg.append("g")
    .attr("transform", `translate(${marginLeft},0)`)
    .call(d3.axisLeft(y));

const parseTime = d3.utcFormat("%Y");

svg.append("line")          // nothing appears
.style("stroke", "black")  
.attr("x1", parseTime(new Date("2007")))     // x position of the first end of the line
.attr("y1", 0.50)      // y position of the first end of the line
.attr("x2", parseTime(new Date("2008")))      // x position of the second end of the line
.attr("y2", 0.40);

container.append(svg.node());

Data from html disappears and doesn’t not post using rest api call. When submit button is selected the form clears and data is not submitted

I have a basic HTML form that submits data to a SharePoint list. There are no errors in the code, nor do I receive anything that would cause the form not to submit to the SharePoint list. I am using basic HTML, some CSS, and AngularJS. The angular code uses a basic rest api call to post the data when the button is selected.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
    <link rel="stylesheet" href="calendar.css">
    <!-- <title>Document</title> -->
</head>
<body>

    <div class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <div class="form-container">
          <h2 class="text-center" style="font-weight: bold;">Tour Request Form</h2>
          <form action="#" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <div ng-controller="calendarController as calendar">
              <label for="tourRequest">Tour Request</label>
                    <input type="text" class="form-control" id="tourRequest" name="tourRequest" required>
                    <input class="btn-primary" type="submit" value="add">


            </div>
            </div>
          </form>
        </div>
      </div>
    </div>
    </div>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="calendar.js"></script>
</body>
</html>
angular.module('mcalendarapp', [])
  .controller('myController', function($scope, $http) {
    $scope.newItem = {
      Title: $scope.tourRequest, // Example: A field in your SharePoint list
     // Description: '' // Example: Another field
    };

    $scope.addItem = function() {
      var listName = 'TourRequest'; // Replace with your list name
      var apiUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('" + listName + "')/items";

      var dataPayload = {
        '__metadata': {
          'type': 'SP.Data.' + listName + 'ListItem' // Adjust if your list name has spaces or special characters
        },
        'Title': $scope.newItem.Title,
       // 'Description': $scope.newItem.Description
      };

      $http({
        method: 'POST',
        url: "/_api/web/lists/getByTitle('mylist')/items",
        headers: {
          'Accept': 'application/json; odata=verbose',
          'Content-Type': 'application/json; odata=verbose',
          'X-RequestDigest': jQuery('#__REQUESTDIGEST').val() // Get the request digest
        },
        data: JSON.stringify(dataPayload)
      }).then(function(response) {
        // Success handling
        alert('Item added successfully!');
        $scope.newItem = {}; // Clear the form
      }).catch(function(error) {
        // Error handling
        console.error('Error adding item:', error);
        alert('Failed to add item. Check console for details.');
      });
    };
  });

Assistance with code and reasoning behind the api call failing