Реализация AMP-страниц
AMP (Accelerated Mobile Pages) — открытый стандарт Google для создания быстрых мобильных страниц. AMP-страницы кэшируются на серверах Google и загружаются мгновенно из поиска. Актуальны для новостных сайтов, блогов и статейных страниц. Google официально убрал AMP как требование для Top Stories (2021), но AMP-контент по-прежнему быстрее отображается на медленных соединениях.
Структура AMP-документа
<!doctype html>
<html ⚡ lang="ru">
<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 на обычную страницу -->
<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 рабочих дней.







