Реалізація AMP-сторінок
AMP (Accelerated Mobile Pages) — відкритий стандарт Google для створення швидких мобільних сторінок. AMP-сторінки кешуються на серверах Google та завантажуються миттєво з пошуку. Актуальні для новинних сайтів, блогів та статейних сторінок. Google офіційно прибрав AMP як вимогу для Top Stories (2021), але AMP-контент все ще швидше відображається на повільних з'єднаннях.
Структура AMP-документа
<!doctype html>
<html ⚡ lang="uk">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<!-- AMP boilerplate -->
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;}</style>
<noscript><style amp-boilerplate>body{-webkit-animation:none}</style></noscript>
<!-- AMP runtime -->
<script async src="https://cdn.ampproject.org/v0.js"></script>
<!-- Canonical посилання на звичайну сторінку -->
<link rel="canonical" href="https://example.com/articles/{{ $article->slug }}">
<!-- Кастомні стилі (тільки inline, макс. 75KB) -->
<style amp-custom>
body { font-family: sans-serif; margin: 0; }
.article { max-width: 680px; margin: 0 auto; padding: 16px; }
h1 { font-size: 1.75rem; line-height: 1.3; }
p { line-height: 1.7; color: #374151; }
</style>
<title>{{ $article->title }}</title>
</head>
<body>
<article class="article">
<h1>{{ $article->title }}</h1>
<!-- AMP-зображення замість звичайного img -->
<amp-img src="{{ $article->cover_url }}"
width="1200" height="630"
layout="responsive"
alt="{{ $article->cover_alt }}">
</amp-img>
<div>{{ $article->content_amp }}</div>
</article>
<!-- AMP Analytics -->
<amp-analytics type="gtag" data-credentials="include">
<script type="application/json">
{
"vars": { "gtag_id": "G-XXXXXXXX" },
"triggers": { "trackPageview": { "on": "visible", "request": "pageview" } }
}
</script>
</amp-analytics>
</body>
</html>
Laravel: генерація AMP-сторінок
// AmpController
class AmpController extends Controller
{
public function article(Article $article): View
{
// Конвертуємо HTML в AMP-сумісний HTML
$ampContent = $this->convertToAmp($article->content);
return view('amp.article', [
'article' => $article,
'amp_content'=> $ampContent,
]);
}
private function convertToAmp(string $html): string
{
// img → amp-img
$html = preg_replace_callback(
'/<img([^>]*)>/i',
function ($matches) {
$attrs = $matches[1];
// Витягуємо width/height або ставимо дефолтні
preg_match('/width=["\']?(\d+)["\']?/i', $attrs, $w);
preg_match('/height=["\']?(\d+)["\']?/i', $attrs, $h);
$width = $w[1] ?? 1200;
$height = $h[1] ?? 630;
return "<amp-img{$attrs} width=\"{$width}\" height=\"{$height}\" layout=\"responsive\"></amp-img>";
},
$html
);
// Видаляємо заборонені теги та атрибути
$html = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $html);
$html = preg_replace('/\s*style\s*=\s*["\'][^"\']*["\']/i', '', $html);
$html = preg_replace('/\s*onclick\s*=\s*["\'][^"\']*["\']/i', '', $html);
return $html;
}
}
Маршрутизація та canonical-зв'язок
// routes/web.php
Route::get('/amp/articles/{article:slug}', [AmpController::class, 'article'])->name('amp.article');
// На звичайній сторінці — link[rel=amphtml]
// У <head>:
<link rel="amphtml" href="{{ route('amp.article', $article) }}">
Валідація AMP
# Встановлення AMP Validator CLI
npm install -g amphtml-validator
# Перевірка сторінки
amphtml-validator https://example.com/amp/articles/my-article
# Перевірка HTML-файлу
amphtml-validator ./public/amp/test.html
Або використовуйте розширення AMP Validator для Chrome.
Що не дозволено в AMP
-
<script>(крім AMP runtime та application/ld+json) - Inline стилі через атрибут style
-
<form>без компонентаamp-form - Зовнішні CSS (тільки inline через
<style amp-custom>) -
document.write(),eval()
Терміни
Реалізація AMP-шаблонів для статей та настройка конвертера HTML→AMP: 3–5 робочих днів.







