Script Management Guide – Adding Custom Scripts to Categories

Script management is at the heart of cookie consent compliance. The ability to control when and how JavaScript code executes based on user consent choices ensures your website respects privacy preferences while maintaining functionality. DigiConsent provides a powerful script management system that lets you assign scripts to specific cookie categories, ensuring they only execute when users grant the appropriate consent.

This comprehensive guide covers everything about managing scripts in DigiConsent: adding scripts to categories, understanding execution timing, handling dependencies, troubleshooting common issues, and implementing advanced script management techniques.

Understanding Script-Based Consent Management

Modern cookie consent works by controlling when scripts execute, not just whether cookies are set.

Why Script Management Matters

Traditional cookie consent approaches only prevented cookie storage, but the tracking scripts still executed, collecting data in memory or sending it to servers before being blocked. Modern consent management controls the scripts themselves:

  • Script blocking: Prevents tracking code from loading until consent is granted
  • Complete control: Stops data collection at the source, not just cookie storage
  • Performance benefit: Declined scripts don’t download or execute, saving bandwidth and CPU
  • Legal compliance: Fully prevents tracking before consent, meeting GDPR requirements

How DigiConsent Manages Scripts

DigiConsent uses script blocking to control execution:

  1. Scripts are assigned to categories (Necessary, Analytics, Marketing, Functional)
  2. Before consent: Scripts in non-necessary categories are blocked from executing
  3. User makes choice: Accepts all, rejects all, or customizes consent
  4. After consent: Scripts in accepted categories execute immediately
  5. Dynamic loading: New scripts can be added dynamically as consent changes

This ensures complete control: no tracking before consent, full functionality after consent.

Adding Scripts to Categories

DigiConsent provides an intuitive interface for adding scripts to each cookie category.

Step-by-Step: Adding a Script

  1. Navigate to DigiConsent > Settings > Cookie Categories
  2. Choose the appropriate category (Necessary, Analytics, Marketing, or Functional)
  3. Click Add Script within that category
  4. Enter a Script Name (e.g., “Google Analytics GA4”, “Facebook Pixel”)
  5. Paste your Script Code in the code editor
  6. Optionally add a Description explaining what the script does
  7. Set Script Position (head or body) if the option is available
  8. Click Save Script

Script Code Requirements

When adding scripts, include the complete script tags:

Correct format (include script tags):

<script>
  // Your JavaScript code here
  console.log('Analytics loaded');
</script>

External scripts:

<script src="https://example.com/analytics.js" async></script>

Multiple scripts can be combined:

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

Always include complete, ready-to-execute code. DigiConsent will handle the blocking and execution timing.

Script Positioning: Head vs. Body

Where scripts are injected affects their execution timing and functionality.

Head Position

Scripts added to the <head> section execute early in page load:

When to use head position:

  • Scripts that need to execute before page content loads
  • Tracking scripts that should capture the earliest user interactions
  • Scripts that define global variables needed by other code
  • Most analytics and marketing pixels (they’re designed for early loading)

Examples for head:

  • Google Analytics
  • Facebook Pixel
  • Google Tag Manager
  • Any tracking that should start immediately

Body Position

Scripts added before the closing </body> tag execute after content loads:

When to use body position:

  • Scripts that manipulate DOM elements (need HTML to load first)
  • Heavy scripts that shouldn’t block page rendering
  • Chat widgets and embedded content
  • Scripts that depend on page content being present

Examples for body:

  • Live chat widgets (Intercom, Zendesk)
  • Video player embeds
  • Interactive features requiring DOM access

Async and Defer Attributes

Control script loading behavior with async and defer:

Async (downloads in parallel, executes when ready):

<script src="analytics.js" async></script>
  • Downloads without blocking HTML parsing
  • Executes as soon as downloaded (may be out of order)
  • Good for independent scripts (analytics, ads)

Defer (downloads in parallel, executes after HTML parsing):

<script src="app.js" defer></script>
  • Downloads without blocking
  • Waits until HTML is parsed before executing
  • Maintains execution order
  • Good for scripts that depend on DOM or other scripts

Most tracking scripts include async by default for performance.

Managing Multiple Scripts in a Category

Cookie categories often contain multiple scripts. Proper organization keeps management simple.

Organization Best Practices

  • Use descriptive names: “Google Analytics GA4” not just “Analytics”
  • Add descriptions: Note what each script does and why it’s needed
  • Group related scripts: Keep base script and event tracking together
  • Document dependencies: Note if scripts must load in specific order

Script Execution Order

DigiConsent executes scripts in the order they’re added to each category:

  1. First script added executes first
  2. Second script added executes second
  3. And so on…

If script B depends on script A, add script A first. Example:

Script 1 (add first): Google Analytics base code

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

Script 2 (add second): Enhanced measurement configuration

<script>
  gtag('config', 'G-XXXXXX', {
    'send_page_view': false,
    'custom_parameter': 'value'
  });
</script>

The second script can safely use gtag() because the first script defined it.

Working with External Script Sources

Many scripts load from external sources (CDNs, third-party services). Special considerations apply.

External Script Example

<script src="https://cdn.example.com/tracking.js"></script>

When this script is in a consent-gated category, DigiConsent blocks it from loading until consent is granted. Once consent is given, the external script downloads and executes.

Common External Scripts by Category

Analytics category:

  • Google Analytics: https://www.googletagmanager.com/gtag/js
  • Hotjar: https://static.hotjar.com/c/hotjar-*.js
  • Matomo: Your self-hosted Matomo instance

Marketing category:

  • Facebook Pixel: https://connect.facebook.net/en_US/fbevents.js
  • LinkedIn: https://snap.licdn.com/li.lms-analytics/insight.min.js
  • TikTok: https://analytics.tiktok.com/i18n/pixel/events.js

Functional category:

  • Intercom: https://widget.intercom.io/widget/*
  • Drift: https://js.driftt.com/include/*
  • YouTube/Vimeo players

Inline Scripts vs. External Scripts

Understanding the difference helps with proper script management.

Inline Scripts

Code written directly in <script> tags:

<script>
  console.log('This is inline JavaScript');
  var myVariable = 'hello';
</script>

Characteristics:

  • No external download needed
  • Executes immediately when encountered
  • Good for configuration and small code snippets
  • Often used with external scripts for configuration

External Scripts

Scripts loaded from a URL:

<script src="https://example.com/script.js"></script>

Characteristics:

  • Must be downloaded before execution
  • Can be cached by browser
  • Better for large libraries and frameworks
  • May load asynchronously

Combining Both

Many services use both together:

<!-- External script loads library -->
<script src="https://analytics.example.com/lib.js" async></script>

<!-- Inline script configures it -->
<script>
  analyticsLib.init({
    apiKey: 'YOUR_KEY',
    settings: {}
  });
</script>

Both parts should be added together to the same category to ensure they execute together.

Advanced Script Management Techniques

Conditional Script Loading

Some scripts should only load under certain conditions:

<script>
// Only load chat widget on product pages
if (document.body.classList.contains('single-product')) {
  // Intercom chat initialization
  window.intercomSettings = { app_id: 'YOUR_APP_ID' };
  // ... rest of Intercom code
}
</script>

This loads the chat widget only on product pages, reducing unnecessary script execution.

User-Specific Scripts

Load different scripts for logged-in vs. logged-out users:

<script>
// Check if user is logged in (example using WordPress)
if (typeof wpUserLoggedIn !== 'undefined' && wpUserLoggedIn) {
  // Load enhanced analytics for logged-in users
  gtag('set', {'user_id': wpUserId});
} else {
  // Standard analytics for anonymous users
  gtag('config', 'G-XXXXXX');
}
</script>

Error Handling in Scripts

Add error handling to prevent one failing script from breaking others:

<script>
try {
  // Your tracking code here
  fbq('init', 'YOUR_PIXEL_ID');
  fbq('track', 'PageView');
} catch(e) {
  console.error('Facebook Pixel failed to load:', e);
  // Optional: Send error to your monitoring system
}
</script>

This prevents errors in Facebook Pixel from breaking other scripts on the page.

Handling Script Dependencies

When scripts depend on each other, careful management ensures they load in the right order.

Sequential Dependencies

If Script B requires Script A to be loaded first:

  1. Add Script A first in DigiConsent
  2. Add Script B second
  3. They’ll execute in that order

Alternatively, check for Script A’s availability before executing Script B:

<script>
// Wait for jQuery to be available before executing
if (typeof jQuery !== 'undefined') {
  jQuery(document).ready(function($) {
    // Your jQuery-dependent code here
  });
} else {
  console.warn('jQuery not loaded, skipping dependent script');
}
</script>

Callback-Based Loading

Some external scripts support callbacks that execute when loading completes:

<script>
// Load script dynamically with callback
function loadScriptWithCallback(src, callback) {
  var script = document.createElement('script');
  script.src = src;
  script.onload = callback;
  document.head.appendChild(script);
}

loadScriptWithCallback('https://example.com/lib.js', function() {
  console.log('Library loaded, now initialize');
  exampleLib.init();
});
</script>

Testing Script Management

Thorough testing ensures scripts execute correctly based on consent.

Testing Checklist

  1. Clear all cookies and cache
  2. Visit site without accepting cookies
  3. Open DevTools → Network tab
  4. Verify no requests to analytics/marketing domains (google-analytics.com, facebook.com, etc.)
  5. Check Console for errors (shouldn’t be any from missing scripts)
  6. Accept appropriate category (e.g., Analytics)
  7. Verify scripts execute (see Network requests, check Console logs)
  8. Test each category independently (Analytics, Marketing, Functional)
  9. Test combined acceptance (Accept All)
  10. Test script functionality (does tracking actually work?)

Debugging Script Issues

Script not executing after consent:

  • Check browser Console for JavaScript errors
  • Verify script code is complete and valid
  • Check script category matches accepted consent
  • Try reloading page after giving consent
  • Check if script requires page reload (some do)

Script executing before consent:

  • Check for duplicate installations (plugin + manual)
  • Verify script is in correct category (not Necessary if it shouldn’t always load)
  • Look for scripts hardcoded in theme files
  • Check other plugins that might load the script

Dependency errors:

  • Ensure dependent scripts load in correct order
  • Add error handling to catch missing dependencies
  • Consider combining dependent scripts into one script block

Best Practices for Script Management

  • Be selective: Only add scripts you actually use and need
  • Name clearly: Use descriptive names for easy identification
  • Document purpose: Add descriptions explaining what each script does
  • Test thoroughly: Test all scenarios (accept, reject, customize)
  • Keep updated: Update scripts when services release new versions
  • Remove unused: Clean up scripts for discontinued services
  • Monitor performance: Check if scripts impact page load speed
  • Use async/defer: Prevent scripts from blocking page rendering
  • Handle errors: Add try/catch blocks to prevent cascading failures
  • Regular audits: Review scripts quarterly to ensure they’re still needed and working

Script Management Checklist

  • All tracking scripts assigned to appropriate categories
  • Script names are descriptive and clear
  • Descriptions added explaining script purpose
  • Scripts with dependencies ordered correctly
  • External scripts use async or defer where appropriate
  • Error handling added to critical scripts
  • No duplicate script installations
  • Scripts tested without consent—none execute
  • Scripts tested with consent—all execute correctly
  • Dependencies load in correct order
  • No console errors from script loading
  • Page performance tested with all scripts loaded
  • Documentation maintained for all scripts
  • Regular audits scheduled to review script necessity

Effective script management is the technical foundation of cookie consent compliance. By properly categorizing scripts, ensuring correct execution timing, handling dependencies thoughtfully, and testing thoroughly, you create a consent system that truly respects user choices while maintaining all the functionality your website needs. The key is organization, testing, and regular maintenance to ensure your script management remains effective as your site evolves.