Performance: Content Security Policy
Content Security Policy (CSP) affects page load speed by controlling which resources the browser can load, impacting render-blocking and resource fetching.
Jump into concepts and practice - no test required
CSP_HEADER = "default-src 'self'; script-src 'self' https://trusted.cdn.com; style-src 'self' https://trusted.cdn.com"CSP_HEADER = "default-src *; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline'"| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Permissive CSP allowing all sources | No direct DOM impact | Multiple reflows due to many external resources | High paint cost from many resources | [X] Bad |
| Strict CSP limiting to self and trusted domains | No direct DOM impact | Fewer reflows due to limited resources | Lower paint cost from fewer resources | [OK] Good |
class CSPMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response['Content-Security-Policy'] = "script-src 'self' https://cdn.example.com"
return responseresponse['Content-Security-Policy'] = "default-src 'self'"What is the likely cause and fix?