Prompt
Script blocking based on consent
Latest observation
Oct 29, 2026
OpenAI APIWeb search: off
To block scripts until a user gives consent, the common pattern is:
- Do not load the script as
type="text/javascript"initially - Store it in a non-executing tag like:
<script type="text/plain" data-consent="analytics" src="..."></script> - After consent is granted, replace or activate it via JavaScript.
Example
<script type="text/plain" data-consent="analytics" src="https://example.com/analytics.js"></script>
<button id="accept">Accept analytics</button>
<script>
document.getElementById('accept').addEventListener('click', function () {
document.querySelectorAll('script[type="text/plain"][data-consent="analytics"]').forEach(function (blockedScript) {
var script = document.createElement('script');
Array.from(blockedScript.attributes).forEach(function (attr) {
if (attr.name !== 'type') {
script.setAttribute(attr.name, attr.value);
}
});
blockedScript.parentNode.replaceChild(script, blockedScript);
});
});
</script>
Important notes
- This works for external scripts and inline scripts.
- If you need to block scripts for privacy/compliance reasons, also consider:
- not rendering the script at all until consent
- delaying any network requests triggered by the script
- ensuring your consent mechanism is compliant with GDPR/ePrivacy or relevant laws
Alternative approach
If you use a consent management platform (CMP), it may provide:
- script classification
- auto-blocking
- consent state handling
- vendor-specific activation
If you want, I can also give you:
- a jQuery version
- a Vanilla JS reusable function
- a Google Tag Manager / Consent Mode setup
- an example for WordPress or Cookiebot