The infamous “Script error.” message is JavaScript error monitoring’s arch nemesis. This generic error appears when browsers block detailed error information from cross-origin scripts due to browser security policy.

Unlike specific error messages that help you debug problems, “Script error.” provides no useful information about what actually went wrong, making it nearly impossible to fix the underlying issue.

This error affects all browsers and occurs whenever you load JavaScript from external domains like CDNs, analytics providers, or third-party widgets.

Script Error is one of the most common JavaScript errors. It frequently ranks in the top 10 in the Global JavaScript Error Statistics.

The Problem

“Script error.” occurs when the browser’s Same-Origin Policy blocks detailed error information from scripts loaded from different origins. An origin is defined as the combination of protocol, domain, and port - so if your website at https://yoursite.com loads JavaScript from a CDN like https://cdn.jsdelivr.net or third-party vendors, those scripts are considered “cross-origin” and subject to error obfuscation. The browser intentionally obscures error details to prevent potential security vulnerabilities.

For example, when a script loaded from a CDN encounters an error like “Cannot read property ‘data’ of undefined” at line 42 of https://cdn.example.com/widget.js, all you see in your error monitoring is the generic “Script error.” message with no filename, line number, or stack trace information.

Important: This security feature protects against information leakage that could enable cross-site attacks, but it makes debugging legitimate errors extremely difficult.

Understanding the Root Cause

“Script error.” can originate from several different scenarios in modern web applications:

1. CDN-Hosted Libraries

Most common scenario: Loading popular libraries from CDNs without proper CORS configuration triggers script errors when those libraries encounter issues.

How to identify: Check if you’re loading JavaScript from domains like cdnjs.cloudflare.com, unpkg.com, or jsdelivr.net without the crossorigin attribute.

2. Third-Party Widgets and Analytics

External services like analytics, chat widgets, social media embeds, or advertising scripts frequently generate script errors that appear generic.

How to identify: Look for script errors that correlate with third-party service usage or user interactions with embedded widgets.

3. Dynamic Script Loading

Modern applications often load scripts dynamically using JavaScript, and these dynamically loaded scripts are subject to the same cross-origin restrictions.

How to identify: Script errors occur during dynamic content loading or after user actions that trigger additional script downloads.

4. Content Security Policy Conflicts

Strict Content Security Policy (CSP) headers can interfere with cross-origin error reporting, even when CORS is properly configured.

How to identify: Check browser console for CSP violation warnings alongside script errors.

5. Modern Bundler and Module Issues

Build tools like Webpack, Vite, or Rollup can create cross-origin scenarios when using code splitting or loading chunks from CDNs.

How to identify: Script errors occur when loading dynamic imports or lazy-loaded components.

6. Browser Extension Interference

Browser extensions often inject scripts that can generate script errors visible to your error monitoring.

How to identify: Script errors that don’t correlate with your code or third-party services you actually use.

How to Fix “Script error.”

Quick Troubleshooting Checklist

  • Add crossorigin="anonymous" to external script tags
  • Verify third-party scripts send proper CORS headers
  • Check Content Security Policy configuration
  • Copy and host scripts on first-party domains
  • Test in private/incognito mode to rule out extensions
  • Monitor for patterns in script error frequency and timing

If basic fixes don’t resolve the issue, follow these systematic steps:

Step 1: Identify Cross-Origin Scripts

Use browser DevTools to identify which scripts are loading from external origins:

  1. Open DevTools Network tab
  2. Reload your page
  3. Filter by JS files
  4. Look for scripts from different domains

// Audit script origins in console
Array.from(document.scripts).forEach(script => {
  const scriptOrigin = new URL(script.src || location.href).origin;
  const pageOrigin = location.origin;

  if (script.src && scriptOrigin !== pageOrigin) {
    console.log('Cross-origin script:', script.src,
                'Has crossorigin?', script.crossOrigin !== null);
  }
});

Step 2: Configure CORS for Static Scripts

Add the crossorigin attribute to script tags loading from external domains:


<!-- Before: Script errors will be generic -->
<script src="https://cdn.jsdelivr.net/npm/react@18/umd/react.min.js"></script>

<!-- After: Detailed error information available -->
<script src="https://cdn.jsdelivr.net/npm/react@18/umd/react.min.js"
        crossorigin="anonymous"></script>

Step 3: Handle Dynamic Script Loading

Configure CORS for dynamically loaded scripts:


// CORS-enabled dynamic loading
function loadScriptWithCORS(url) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.crossOrigin = 'anonymous'; // Enable CORS

    script.onload = () => resolve(script);
    script.onerror = (error) => {
      console.error('Script loading failed:', url, error);
      reject(error);
    };

    document.head.appendChild(script);
  });
}

// Usage
loadScriptWithCORS('https://cdn.example.com/widget.js')
  .then(() => console.log('Script loaded successfully'))
  .catch(error => console.error('Failed to load script:', error));

Step 4: Configure Server-Side CORS Headers

Ensure your servers (and third-party services) send appropriate CORS headers:


// Express.js server configuration
app.use('/static/js', (req, res, next) => {
  // Allow any origin to load with CORS
  res.header('Access-Control-Allow-Origin', '*');
  // Or restrict to specific domains
  // res.header('Access-Control-Allow-Origin', 'https://yourdomain.com');

  res.header('Access-Control-Allow-Methods', 'GET');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

Step 5: Handle Bundler and Build Tool Scenarios

Webpack configuration:


// webpack.config.js
module.exports = {
  output: {
    crossOriginLoading: 'anonymous', // Enable CORS for dynamic imports
    publicPath: 'https://cdn.yourdomain.com/assets/'
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        }
      }
    }
  }
};

Vite configuration:


// vite.config.js
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom']
        }
      }
    }
  },
  experimental: {
    renderBuiltUrl(filename, { hostType }) {
      if (hostType === 'js') {
        return {
          relative: false,
          runtime: `window.__assetsPath + ${JSON.stringify(filename)}`
        };
      }
    }
  }
});

Step 6: Implement Comprehensive Error Handling

Even when browsers hide the actual error details, TrackJS captures additional metadata and telemetry that helps you understand what the real issue is. This includes user actions leading up to the error, browser information, and network request patterns that provide context even without the specific error message.

Step 7: Configure Content Security Policy

Ensure your CSP allows cross-origin script loading while maintaining security:


<!-- Restrictive CSP that allows specific CDNs -->
<meta http-equiv="Content-Security-Policy"
      content="
        default-src 'self';
        script-src 'self' 'unsafe-inline'
                   https://cdn.jsdelivr.net
                   https://cdnjs.cloudflare.com
                   https://unpkg.com;
        connect-src 'self' https://api.yourdomain.com;
      ">

<!-- More permissive for development -->
<meta http-equiv="Content-Security-Policy"
      content="
        default-src 'self';
        script-src 'self' 'unsafe-inline' 'unsafe-eval' *;
        connect-src *;
      ">

Step 8: Monitor and Filter Script Errors

Implement intelligent monitoring that distinguishes between actionable errors and noise. Error monitoring services like TrackJS can help filter and categorize script errors, providing better visibility into which ones represent real problems versus browser extension interference or third-party service issues.

Focus monitoring efforts on script errors that correlate with user-reported problems or specific application functionality failures.

When to Ignore This Error

“Script error.” can often be safely ignored in these scenarios:

  • Browser extension interference: Errors from extensions users have installed
  • Third-party advertising scripts: Ad network errors outside your control
  • Social media widgets: Occasional errors from embedded social content
  • Analytics script hiccups: Temporary issues with tracking scripts

However, investigate further if you notice:

  • High frequency: Many script errors from the same source
  • User impact correlation: Script errors coinciding with user-reported problems
  • Core functionality affected: Errors that break essential application features
  • Sudden increases: Spikes in script errors after deployments

Summary

“Script error.” is a browser security feature that obscures error details from cross-origin scripts. The solution involves configuring CORS properly using the crossorigin attribute on script tags and ensuring servers send appropriate CORS headers.

Modern web applications using CDNs, third-party services, or dynamic script loading must proactively address cross-origin error reporting to maintain effective error monitoring. The key is balancing security with observability through proper CORS configuration.

Remember: Not all script errors represent problems you can or should fix - focus on those that impact your application’s core functionality and user experience.

TrackJS is the easy way to monitor your JavaScript applications and fix production errors. TrackJS is provides detailed error monitoring and alerting to developers around the world at companies like 3M, Tidal, IKEA, Venmo, Allbirds, and Frontend Masters. TrackJS catches millions of errors from users everyday. Let's start catching yours.

Protect your JavaScript