vite-for-wp icon indicating copy to clipboard operation
vite-for-wp copied to clipboard

Script Type Module Not Applied Due to URL Parameter Mismatch

Open multiplehats opened this issue 10 months ago • 1 comments

The set_script_type_attribute function fails to add type="module" to script tags when URL parameters are present in the src attribute. This occurs particularly with optimization plugins (like SiteGround Optimizer) that add URL parameters such as ?siteground-async=1.

Current Behavior

When comparing script sources:

// Source URL from WordPress
src = "https://example.com/script.js?siteground-async=1"
// Actual script tag URL
current_src = "https://example.com/script.js"
// Direct comparison fails
if ($current_src === $src) // Never matches

Expected Behavior

The function should match script tags regardless of URL parameters, ensuring type="module" is properly added to ES module scripts.

Proposed Solution

Update the source comparison in set_script_type_attribute to strip URL parameters:

function set_script_type_attribute(string $target_handle, string $tag, string $handle, string $src): string {
    if ($target_handle !== $handle) {
        return $tag;
    }
    
    $processor = new WP_HTML_Tag_Processor($tag);
    
    // Strip URL parameters for comparison
    $clean_src = preg_replace('/\?.$/', '', $src);
    
    while ($processor->next_tag('script')) {
        $current_src = $processor->get_attribute('src');
        if ($current_src) {
            // Strip URL parameters for comparison
            $clean_current_src = preg_replace('/\?.$/', '', $current_src);
            if ($clean_current_src === $clean_src) {
                $processor->set_attribute('type', 'module');
                break;
            }
        }
    }
    
    return $processor->get_updated_html();
}

Environment

  • WordPress version: 6.4+
  • PHP version: 8.0+
  • Vite for WP version: ^0.10.0
  • Related plugins: SiteGround Optimizer (but issue affects any plugin that adds URL parameters)

Additional Context

This issue causes ES module scripts to fail with the error "Cannot use import statement outside a module" because the type="module" attribute isn't being added when URL parameters are present.

multiplehats avatar Jan 30 '25 16:01 multiplehats

Did you get a chance to look at this @kucrut ? Happy to make a PR, but I'd love if you can confirm prior to make making the PR>

multiplehats avatar Aug 19 '25 12:08 multiplehats