Script Injection

Inject scripts into HTML responses at the edge.


Overview

Script Injection lets you add JavaScript, analytics, or other code to your HTML pages without modifying your origin. Scripts are injected at the CDN edge during delivery.


Use Cases

  • Analytics: Google Analytics, Plausible, Mixpanel
  • Chat widgets: Intercom, Drift, Crisp
  • A/B testing: Optimizely, VWO
  • Tag managers: Google Tag Manager
  • Performance monitoring: New Relic, Datadog
  • Consent banners: Cookie consent scripts

How It Works

  1. Visitor requests an HTML page
  2. CDN fetches from origin (or cache)
  3. Scripts are injected into the HTML
  4. Modified page is returned to visitor

Injection happens in real-time during delivery.


Creating Scripts

From Dashboard

  1. Go to your zone settings
  2. Click "Scripts" tab
  3. Click "Add Script"
  4. Configure the script
  5. Save changes

Script Options

Name: A descriptive name for the script.

Content: The HTML/JavaScript code to inject.

Placement:

  • head: Inject before </head>
  • body: Inject before </body>

Enabled: Toggle to enable/disable without deleting.


Example Scripts

Google Analytics 4

Placement: head

<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXX');
</script>

Google Tag Manager

Placement: head

<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');
</script>

Intercom Chat

Placement: body

<script>
  window.intercomSettings = {
    api_base: "https://api-iam.intercom.io",
    app_id: "xxxxxxxx"
  };
</script>
<script>
(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',w.intercomSettings);}else{var d=document;var i=function(){i.c(arguments);};i.q=[];i.c=function(args){i.q.push(args);};w.Intercom=i;var l=function(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/xxxxxxxx';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);};if(document.readyState==='complete'){l();}else if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})();
</script>

Cookie Consent

Placement: body

<script src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js"></script>
<script>
window.cookieconsent.initialise({
  palette: {
    popup: { background: "/docs/1.0/features/script-injection#1d1d1d" },
    button: { background: "/docs/1.0/features/script-injection#f97316" }
  },
  content: {
    message: "We use cookies to improve your experience.",
    dismiss: "Got it!",
    link: "Learn more",
    href: "/privacy"
  }
});
</script>

Exclusion Rules

Prevent scripts from being injected on specific pages:

Path Exclusions

Exclude specific paths from injection:

/admin/*           # Skip admin pages
/api/*             # Skip API routes
/embed/*           # Skip embed pages
/print/*           # Skip print versions

URL Patterns

Use wildcards or exact matches:

/checkout          # Exact match
/checkout/*        # Pattern match
*.pdf              # File extension

Script Templates

NordicCDN provides pre-configured templates for common services:

  • Google Analytics 4
  • Google Tag Manager
  • Facebook Pixel
  • Hotjar
  • Intercom
  • Crisp
  • Plausible

Select a template and enter your ID/API key.


Order of Execution

When multiple scripts are injected:

  1. Head scripts inject in order defined
  2. Body scripts inject in order defined
  3. Scripts within same placement execute in order

Ensure dependencies are ordered correctly (e.g., jQuery before plugins).


Caching Behavior

When scripts are modified:

  1. Zone cache is automatically purged
  2. New requests get updated scripts
  3. No manual cache purge needed

Best Practices

1. Use Async/Defer

Load scripts asynchronously to avoid blocking:

<script async src="..."></script>
<script defer src="..."></script>

2. Minimize Injected Code

Keep injected scripts small. For large scripts:

  • Host on your CDN
  • Reference via <script src="...">
  • Let the CDN cache the external file

3. Test Performance Impact

After adding scripts:

  1. Test page load speed
  2. Check for layout shifts
  3. Monitor Core Web Vitals

4. Use Exclusions Wisely

Exclude scripts from:

  • Admin/dashboard pages
  • API endpoints
  • Print stylesheets
  • Pages where scripts aren't needed

Troubleshooting

Script Not Appearing

  1. Verify script is enabled
  2. Check exclusion rules aren't matching
  3. Verify page is served through CDN
  4. Check Content-Type is text/html
  5. Clear CDN cache

Script Breaking Page

  1. Check for JavaScript errors in console
  2. Verify script content is valid HTML/JS
  3. Check for conflicts with existing scripts
  4. Test script in isolation

Double Injection

If scripts appear twice:

  1. Verify script isn't in origin AND injected
  2. Check for duplicate script entries
  3. Review caching behavior

Scripts Affecting Layout

  1. Add scripts to body (not head) if they modify DOM
  2. Use defer attribute
  3. Wait for DOMContentLoaded before modifying