Course contentsShow
← Web Development
Lesson 2971 of 2,98253. Privacy and ComplianceFree lesson

Blocking Scripts Based on Consent

Conditionally loading third-party scripts and pixels only after receiving appropriate user consent.

Blocking Scripts Based on Consent

What you'll learn: How to prevent third-party tracking scripts and pixels from loading until users explicitly grant permission.

The Problem

Analytics, advertising pixels, and social media widgets load automatically when embedded in your HTML with standard <script> tags. But privacy laws like GDPR and CCPA require that non-essential scripts wait for user consent before executing. Simply displaying a cookie banner isn't enough—you must actually block the scripts.

How It Works

The technique is straightforward: don't let the browser recognize script tags as executable code until consent is granted.

Before consent:

<!-- Use a non-script type to prevent execution -->
<script type="text/plain" data-consent-category="analytics">
  // Google Analytics code here
  gtag('config', 'GA_MEASUREMENT_ID');
</script>

The type="text/plain" tells the browser "this isn't JavaScript, ignore it." The data-consent-category attribute lets you organize scripts by purpose (analytics, marketing, etc.).

After consent: When the user accepts analytics cookies (based on your consent choice implementation from the previous lesson), your consent manager activates these scripts:

// Find all blocked analytics scripts
const scripts = document.querySelectorAll('[data-consent-category="analytics"]');

scripts.forEach(script => {
  const newScript = document.createElement('script');
  newScript.textContent = script.textContent;
  script.parentNode.replaceChild(newScript, script);
});

This creates proper <script> tags that execute immediately, but only after the user's consent has been recorded.

Think of It Like a Locked Door

Imagine third-party scripts as visitors at a locked door. The type="text/plain" is the lock. Only when the user hands you the key (consent) do you unlock the door and let them in.

Key Takeaway: Block third-party scripts by using type="text/plain" and custom data attributes, then programmatically convert them to executable scripts only after receiving appropriate user consent for that category.