Refactor high-complexity React components in Dify frontend. Use when `pnpm analyze-component...
npx skills add echohtp/google-adsense-best-practices-skill
Or install specific skill: npx add-skill https://github.com/echohtp/google-adsense-best-practices-skill
# Description
Comprehensive guide for implementing Google AdSense with best practices
# SKILL.md
AdSense Best Practices Skill
Overview
This skill provides comprehensive guidance for implementing Google AdSense in web applications using any technology stack—vanilla HTML/JavaScript, React, Next.js, Vue, Angular, or other frameworks. It covers compliance, optimization, user experience, and performance considerations.
Core Principles
1. Policy Compliance
- Read the AdSense Program Policies: Familiarize yourself with Google's publisher policies before implementation
- No Invalid Traffic: Never use bots, auto-refresh, or artificially inflate impressions/clicks
- Content Quality: Maintain high-quality, original content
- Prohibited Content: Ensure site doesn't contain adult content, violence, hateful content, or other prohibited material
- Ad Placement Restrictions: Don't place ads in misleading locations or hide them
2. Ad Placement Strategy
- Above the Fold: Place 1 responsive ad unit above the fold for high visibility
- Natural Content Flow: Integrate ads contextually within content, not forcing them
- Spacing: Maintain at least 6px padding around ad units
- Content-to-Ad Ratio: Keep 60% content / 40% ads maximum; prioritize content
- Ad Density: Use no more than 3 ad units per page on desktop, fewer on mobile
- Anchor Ads: Use only on mobile, and only 1 per page
- In-Article Ads: Great for long-form content; place between paragraphs, never within text
- Sidebar Placement: Effective for secondary content areas
3. Responsive Design Implementation
// Always use responsive ad units for better performance across devices
// Responsive units automatically adjust to fit their container
// DO use responsive ads
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
data-ad-slot="1234567890"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
// DON'T use fixed-size ads for all devices
// Fixed ads can create poor UX on mobile
4. Performance Optimization
- Lazy Loading: Implement lazy loading for off-screen ad units to reduce initial page load
- Async Script Loading: Always load the Google AdSense script asynchronously
- Minimal Render Blocking: Avoid blocking page rendering with ad loading
- Code Splitting: In SPAs (React/Next.js), code-split ad loading
- Deferred Script Execution: Defer non-critical ad scripts
5. Technology-Specific Implementations
Vanilla HTML/JavaScript
<!-- Async script loading (best practice) -->
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxxxx"
crossorigin="anonymous"></script>
<!-- Responsive display ad -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
data-ad-slot="1234567890"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<!-- Push ad initialization after DOM ready -->
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
React / Next.js Implementation
// Create a reusable AdSense component
// 1. Create AdUnit.jsx component
import { useEffect } from 'react';
export const AdUnit = ({
adSlot,
format = 'auto',
fullWidth = true,
className = ''
}) => {
useEffect(() => {
// Push ad initialization only when component mounts
if (window.adsbygoogle === undefined) return;
try {
(window.adsbygoogle = window.adsbygoogle || []).push({});
} catch (err) {
console.error('AdSense error:', err);
}
}, []);
return (
<ins
className={`adsbygoogle ${className}`}
style={{ display: 'block' }}
data-ad-client={process.env.NEXT_PUBLIC_ADSENSE_CLIENT_ID}
data-ad-slot={adSlot}
data-ad-format={format}
data-full-width-responsive={fullWidth}
/>
);
};
// 2. Add script to _document.js (Next.js) or main HTML
// In _document.js:
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
<Html>
<Head>
<script
async
src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_ADSENSE_CLIENT_ID}`}
crossOrigin="anonymous"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
// 3. Usage in pages
import { AdUnit } from '@/components/AdUnit';
export default function Article() {
return (
<article>
<h1>Your Article Title</h1>
{/* Above the fold */}
<AdUnit adSlot="1234567890" />
<p>Article content...</p>
{/* In-article ad */}
<AdUnit adSlot="0987654321" />
<p>More content...</p>
</article>
);
}
Vue / Nuxt Implementation
// AdSense.vue component
<template>
<ins
class="adsbygoogle"
style="display: block"
:data-ad-client="adClient"
:data-ad-slot="adSlot"
:data-ad-format="format"
:data-full-width-responsive="fullWidth"
/>
</template>
<script>
export default {
name: 'AdSense',
props: {
adSlot: {
type: String,
required: true
},
format: {
type: String,
default: 'auto'
},
fullWidth: {
type: [Boolean, String],
default: true
}
},
data() {
return {
adClient: process.env.VUE_APP_ADSENSE_CLIENT_ID
}
},
mounted() {
this.$nextTick(() => {
if (window.adsbygoogle) {
(window.adsbygoogle = window.adsbygoogle || []).push({});
}
});
}
}
</script>
6. Environment Variables & Security
- Never hardcode client IDs: Use environment variables
- Protect credentials: Use
.env.local(not committed to version control) - Server-side validation: Validate ad placement programmatically if needed
- Client ID structure:
ca-pub-XXXXXXXXXXXXXXXX
# .env.local
NEXT_PUBLIC_ADSENSE_CLIENT_ID=ca-pub-xxxxxxxxxxxxxxxx
7. Lazy Loading Implementation
// Use Intersection Observer for lazy loading ads
const lazyLoadAds = () => {
if ('IntersectionObserver' in window) {
const adObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
if (window.adsbygoogle) {
(window.adsbygoogle = window.adsbygoogle || []).push({});
}
adObserver.unobserve(entry.target);
}
});
});
document.querySelectorAll('.adsbygoogle').forEach(ad => {
adObserver.observe(ad);
});
}
};
// Call after DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', lazyLoadAds);
} else {
lazyLoadAds();
}
8. Mobile Optimization
- Responsive Units: Always use responsive ad format
- Touch-Friendly: Ensure ads don't interfere with touch interactions
- Viewport Meta Tag: Include
<meta name="viewport" content="width=device-width, initial-scale=1"> - Anchor Ads: Consider for mobile-specific placement (max 1 per page)
- Mobile-First: Test on actual mobile devices
- Performance: Minimize ad impact on Core Web Vitals (LCP, FID, CLS)
9. Troubleshooting Common Issues
| Issue | Solution |
|---|---|
| Ads not showing | Check Publisher ID, verify account approval, ensure browser allows scripts |
| Low CTR | Review placement, optimize content relevance, check targeting |
| High bounce rate | Ads too intrusive; adjust placement and sizing |
| CLS (Layout Shift) | Use fixed container heights for ad units, avoid dynamic resizing |
| Script errors | Ensure async script loads before ad initialization |
| Invalid traffic warnings | Review bot traffic, implement rate limiting, verify user patterns |
10. Monitoring & Analytics
- Track Performance: Monitor CTR, RPM (Revenue Per Mille), and CPM
- Use Google Analytics: Integrate with GA to track user behavior
- Ad.Balance Tool: Use Google's tool to optimize ad density
- AdSense Reports: Monitor earnings, page RPM, and impressions
- A/B Testing: Test different ad placements and formats
- Core Web Vitals: Monitor page speed impact from ads
11. Privacy & GDPR Compliance
- Consent Management: Implement consent banner for EU users
- Privacy Policy: Update to disclose AdSense usage
- Data Disclosure: Inform users about personalized ads
- User Controls: Allow users to manage ad preferences
- Non-personalized Ads: Option for serving non-personalized ads
12. Best Practices Checklist
- ✓ Account approved by Google AdSense
- ✓ Responsive ad units implemented
- ✓ Async script loading enabled
- ✓ No more than 3 ad units per page
- ✓ Ads placed in contextually relevant areas
- ✓ Mobile optimization verified
- ✓ Environment variables used for credentials
- ✓ Core Web Vitals not negatively impacted
- ✓ Privacy policy updated
- ✓ GDPR/consent handling implemented
- ✓ Performance monitoring enabled
- ✓ Invalid traffic prevention measures in place
Common Mistakes to Avoid
- Too many ads: Exceeds density limits and hurts user experience
- Misleading placement: Ads disguised as content violates policies
- Automatic refreshing: Artificially increases impressions—forbidden
- Blocking ads: Don't hide ads or use CSS to obscure them
- Encouraging clicks: Never ask users to click ads
- Testing in production: Use AdSense Test Publisher ID for development
- Fixed ad sizes only: Mobile users get poor experience
- Ignoring analytics: Don't monitor performance
- Poor content quality: Low-quality sites get lower CPM
- Hardcoding credentials: Security risk if code is public
Additional Resources
# README.md
Google AdSense Best Practices 🚀
Comprehensive guide for implementing Google AdSense the right way across any technology stack. Includes policy compliance, performance optimization, and implementation examples for vanilla JavaScript, React, Next.js, Vue, and more.
📋 Overview
This repository provides:
✅ Complete best practices based on Google's official policies
✅ Multi-framework examples (React, Next.js, Vue, vanilla JS)
✅ Production-ready code with error handling
✅ Performance optimization tips and techniques
✅ Troubleshooting guide for common issues
✅ Compliance checklist for policy adherence
🚀 Quick Start
1. Setup (30 seconds)
# Clone the repo
git clone https://github.com/echohtp/google-adsense-best-practices-skill.git
cd google-adsense-best-practices-skill
# Copy environment template
cp .env.example .env.local
# Add your Publisher ID (get from: https://www.google.com/adsense/)
# NEXT_PUBLIC_ADSENSE_CLIENT_ID=ca-pub-xxxxxxxxxxxxxxxx
2. Choose Your Framework
- Next.js: See
NextJsExample.tsx - React: See
ReactExample.jsx - Vanilla JS: See
VanillaJSExample.html - Any Framework: Use
AdSenseManager.js
3. Implement
// React / Next.js example
import { AdUnit } from '@/components/AdUnit';
export default function Page() {
return (
<article>
<h1>My Article</h1>
<AdUnit adSlot="1234567890" />
<p>Content...</p>
</article>
);
}
For detailed setup, see INSTALLATION.md
📁 Documentation
Core Files
| File | Purpose | Read Time |
|---|---|---|
| SKILL.md | Comprehensive best practices & implementation | 30 min |
| QUICK_REFERENCE.md | Quick lookup & checklists | 10 min |
| TROUBLESHOOTING.md | Debugging & issue resolution | 20 min |
| INSTALLATION.md | Step-by-step setup guide | 15 min |
Example Implementations
| File | Framework | Complexity |
|---|---|---|
| VanillaJSExample.html | Vanilla HTML/JS | ⭐ Easy |
| ReactExample.jsx | React | ⭐⭐ Medium |
| NextJsExample.tsx | Next.js | ⭐⭐ Medium |
| AdSenseManager.js | Framework-agnostic | ⭐⭐⭐ Advanced |
🎯 Key Features
✅ Policy Compliance
- Follows all Google AdSense Program Policies
- Ad density validation (max 3 per page)
- Invalid traffic prevention
- Content quality guidelines
✨ Performance Optimization
- Lazy loading with Intersection Observer
- Async script loading
- Layout shift prevention (CLS < 0.1)
- Core Web Vitals monitoring
🔒 Security & Privacy
- Environment variables (never hardcode credentials)
- Error handling & try/catch
- GDPR compliance ready
- Privacy policy templates
📱 Responsive Design
- Mobile-first approach
- Touch-friendly ad placement
- Responsive ad formats
- Device testing guidelines
🛠️ Framework Support
| Framework | Status | Example | Docs |
|---|---|---|---|
| Next.js | ✅ Full | NextJsExample.tsx | INSTALLATION.md |
| React | ✅ Full | ReactExample.jsx | INSTALLATION.md |
| Vue/Nuxt | ✅ Full | SKILL.md | INSTALLATION.md |
| Vanilla JS | ✅ Full | VanillaJSExample.html | INSTALLATION.md |
| Angular | ✅ Full | AdSenseManager.js | SKILL.md |
| Svelte | ✅ Full | AdSenseManager.js | SKILL.md |
📊 Implementation Checklist
Before going live, ensure:
✅ AdSense account approved
✅ Publisher ID obtained and configured
✅ Environment variables setup (.env.local)
✅ Async script loading enabled
✅ Max 3 ad units per page
✅ Responsive ad format used
✅ ads.txt file created
✅ Privacy policy updated
✅ Tested on multiple devices
✅ Core Web Vitals acceptable
✅ Error handling implemented
✅ Monitoring setup complete
✅ No hardcoded credentials
See QUICK_REFERENCE.md for full checklist.
🚨 Common Mistakes to Avoid
| ❌ Wrong | ✅ Correct |
|---|---|
| Hardcode client ID | Use environment variables |
| Synchronous script | Async script loading |
| Auto-refresh ads | Load once per page |
| More than 3 ads | Max 3 ads per page |
| No error handling | Try/catch implemented |
| No ads.txt | Create /ads.txt |
| Fixed sizes only | Responsive format |
| No privacy update | Update privacy policy |
📈 Performance Tips
Lazy Load Ads
// Ads load only when visible
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Load ad
(window.adsbygoogle || []).push({});
}
});
});
Reserve Ad Space
.ad-container {
min-height: 280px; /* Prevent layout shift */
margin: 1rem 0;
}
Monitor Core Web Vitals
- LCP (Largest Contentful Paint): < 2.5s
- FID (First Input Delay): < 100ms
- CLS (Cumulative Layout Shift): < 0.1
More tips in SKILL.md
🧪 Testing
Verify Installation
// Check AdSense loaded
console.log('AdSense loaded:', !!window.adsbygoogle);
// Check ad count
console.log('Ads on page:', document.querySelectorAll('.adsbygoogle').length);
// Check ad attributes
document.querySelectorAll('.adsbygoogle').forEach((ad, i) => {
console.log(`Ad ${i}:`, {
slot: ad.getAttribute('data-ad-slot'),
format: ad.getAttribute('data-ad-format'),
client: ad.getAttribute('data-ad-client')
});
});
Test in Incognito
- Open in private/incognito mode
- Disable ad blockers
- Wait 30 seconds for test ads
- Should see ad content
See TROUBLESHOOTING.md for comprehensive testing guide.
📚 Learning Path
- Start (10 min): Read QUICK_REFERENCE.md
- Understand (30 min): Read SKILL.md
- Implement (30 min): Follow INSTALLATION.md
- Verify (20 min): Test with TROUBLESHOOTING.md
- Launch (10 min): Use pre-launch checklist
- Monitor (ongoing): Track metrics in AdSense
🔗 Resource Links
Official Google AdSense
Documentation & Policies
Performance Tools
🤝 Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
Quick Links
📄 License
MIT License - see LICENSE file for details.
This project is not affiliated with Google Inc. All implementations follow Google's official policies and best practices.
⚠️ Disclaimer
This repository provides guidance based on Google's official policies. Users are responsible for:
- ✅ Maintaining an approved AdSense account
- ✅ Following all AdSense Program Policies
- ✅ Ensuring content quality and relevance
- ✅ Monitoring traffic patterns
- ✅ Complying with privacy regulations (GDPR, CCPA, etc.)
- ✅ Maintaining compliance with all applicable laws
For official guidance, always refer to:
- https://support.google.com/adsense
- https://www.google.com/adsense/policies
📞 Support
Getting Help
- Check Docs: Review TROUBLESHOOTING.md
- Search Issues: Look for similar problems
- Create Issue: Report bugs or ask questions
- Contact Google: For AdSense-specific support: https://support.google.com/adsense
Quick Links
🌟 Show Your Support
If this guide helped you, please consider:
- ⭐ Star this repository
- 📤 Share with others
- 🐛 Report issues
- 💡 Suggest improvements
- 🤝 Contribute enhancements
Last Updated: November 2025
Status: Production Ready ✅
Version: 1.0.0
For questions, issues, or contributions, visit the Issues page.
Made with ❤️ for web developers
# Supported AI Coding Agents
This skill is compatible with the SKILL.md standard and works with all major AI coding agents:
Learn more about the SKILL.md standard and how to use these skills with your preferred AI coding agent.