This is page 15 of 20. Use http://codebase.md/cloudflare/docs/imgs/%7B%7Bg.url(parentDoc.pod_path,%20locale=usedDoc.locale).path%7D%7D?lines=false&page={x} to view the full context.
# Directory Structure
```
├── .editorconfig
├── .eslintrc.json
├── .firebaserc
├── .github
│ └── workflows
│ └── semgrep.yml
├── .gitignore
├── .travis.yml
├── assets
│ ├── extra
│ │ └── brand_assets.zip
│ ├── img
│ │ ├── about
│ │ │ ├── case-studies
│ │ │ │ └── bg_lines.png
│ │ │ ├── design-principles
│ │ │ │ ├── bg1.svg
│ │ │ │ ├── bg2.svg
│ │ │ │ ├── design_icon_break.svg
│ │ │ │ ├── design_icon_fast.svg
│ │ │ │ ├── design_icon_future.svg
│ │ │ │ ├── design_icon_layers.svg
│ │ │ │ ├── design_icon_priorities.svg
│ │ │ │ ├── design_icon_ux.svg
│ │ │ │ ├── design_icon_whitelist.svg
│ │ │ │ ├── lines1.svg
│ │ │ │ └── lines2.svg
│ │ │ ├── how-amp-works
│ │ │ │ ├── line_behind.svg
│ │ │ │ └── lines_front.svg
│ │ │ ├── overview
│ │ │ │ ├── bg2.svg
│ │ │ │ ├── herobg.svg
│ │ │ │ ├── herolines1.svg
│ │ │ │ ├── herolines2.svg
│ │ │ │ ├── line4.svg
│ │ │ │ ├── lines3.svg
│ │ │ │ ├── what_phone.png
│ │ │ │ ├── what_phone@1_5x.png
│ │ │ │ └── [email protected]
│ │ │ └── who-use-amp
│ │ │ ├── adtech
│ │ │ │ ├── adtech_icon_customize.svg
│ │ │ │ ├── adtech_icon_intro.svg
│ │ │ │ ├── adtech_icon_reach.svg
│ │ │ │ ├── adtech_icon_revenue.svg
│ │ │ │ ├── indexexchange_logo.png
│ │ │ │ ├── lines.svg
│ │ │ │ ├── sharethrough_logo.png
│ │ │ │ ├── teads_logo.svg
│ │ │ │ └── triplelift_logo.png
│ │ │ ├── advertisers
│ │ │ │ ├── advertiser_phone_wired.png
│ │ │ │ ├── advertiser_phone_wired@1_5x.png
│ │ │ │ ├── [email protected]
│ │ │ │ ├── advertisers_bg.svg
│ │ │ │ ├── advertisers_icon_audience.svg
│ │ │ │ ├── advertisers_icon_everywhere.svg
│ │ │ │ ├── advertisers_icon_intro.svg
│ │ │ │ ├── advertisers_icon_ROI.svg
│ │ │ │ └── advertisers_lines.svg
│ │ │ ├── amp-ads
│ │ │ │ ├── ads_icon.svg
│ │ │ │ ├── cloudflare_logo.png
│ │ │ │ ├── doubleclick_logo.png
│ │ │ │ ├── google_logo.png
│ │ │ │ ├── lines_bottom1.svg
│ │ │ │ ├── lines_bottom2.svg
│ │ │ │ ├── lines.svg
│ │ │ │ ├── roi_icon.svg
│ │ │ │ ├── speed_icon.svg
│ │ │ │ └── triplelift_logo.png
│ │ │ ├── card_developers.png
│ │ │ ├── card_developers.svg
│ │ │ ├── card_smb.png
│ │ │ ├── card_smb.svg
│ │ │ ├── hero_triangle.png
│ │ │ ├── publishers
│ │ │ │ ├── globo_logo.svg
│ │ │ │ ├── nyt_logo.svg
│ │ │ │ ├── publisher_icon_business.svg
│ │ │ │ ├── publisher_icon_fast.svg
│ │ │ │ ├── publisher_icon_intro.svg
│ │ │ │ ├── publisher_icon_simple.svg
│ │ │ │ ├── publisher_phone_cnn.png
│ │ │ │ ├── publisher_phone_cnn@1_5x.png
│ │ │ │ ├── [email protected]
│ │ │ │ ├── wapo_logo.png
│ │ │ │ └── wired_logo.png
│ │ │ ├── who_icon_adtech.svg
│ │ │ ├── who_icon_advertisers.svg
│ │ │ ├── who_icon_publishers.svg
│ │ │ ├── who_lines1.svg
│ │ │ ├── who_lines2.svg
│ │ │ ├── who_phones_hero.png
│ │ │ ├── who_phones_hero@1_5x.png
│ │ │ └── [email protected]
│ │ ├── amp_favicon.png
│ │ ├── amp-conf
│ │ │ └── speakers
│ │ │ ├── alex.jpg
│ │ │ ├── ali.jpg
│ │ │ ├── ardan.jpg
│ │ │ ├── beck.jpg
│ │ │ ├── bez.jpg
│ │ │ ├── chen.jpg
│ │ │ ├── dane.jpg
│ │ │ ├── eric.jpg
│ │ │ ├── gina.jpg
│ │ │ ├── honey.jpg
│ │ │ ├── jeremy.jpg
│ │ │ ├── john.jpg
│ │ │ ├── le.jpg
│ │ │ ├── madison.jpg
│ │ │ ├── malte.jpg
│ │ │ ├── malteandrudy.jpg
│ │ │ ├── mariko.jpg
│ │ │ ├── matthew.jpg
│ │ │ ├── mike.jpg
│ │ │ ├── natalia.jpg
│ │ │ ├── nicole.jpg
│ │ │ ├── paul.jpg
│ │ │ ├── ranna.jpg
│ │ │ ├── richard.jpg
│ │ │ ├── rudy.jpg
│ │ │ ├── sam.jpg
│ │ │ ├── sarah.jpg
│ │ │ ├── sebastian.jpg
│ │ │ ├── senthil.jpg
│ │ │ ├── sriram.jpg
│ │ │ ├── vadim.jpg
│ │ │ ├── vamsee.jpg
│ │ │ ├── will.jpg
│ │ │ └── yamini.jpg
│ │ ├── arrow-blue.svg
│ │ ├── arrow.svg
│ │ ├── background.jpg
│ │ ├── blog-icon.svg
│ │ ├── brand-guidelines.pdf
│ │ ├── case-studies
│ │ │ ├── gizmodo_logo.png
│ │ │ ├── gizmodo_phone1.png
│ │ │ ├── gizmodo_phone1@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── gizmodo_phone2.png
│ │ │ ├── gizmodo_phone2@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── gizmodo_thumb.jpg
│ │ │ ├── gizmodo.pdf
│ │ │ ├── hearst_framed.png
│ │ │ ├── hearst_framed2.png
│ │ │ ├── hearst_logo.png
│ │ │ ├── hearst_thumb.jpg
│ │ │ ├── hearst.pdf
│ │ │ ├── milestone_home_framed.png
│ │ │ ├── milestone_logo.png
│ │ │ ├── milestone_search_framed.png
│ │ │ ├── milestone_thumb.jpg
│ │ │ ├── milestone.pdf
│ │ │ ├── plista_graphic.png
│ │ │ ├── plista_logo.png
│ │ │ ├── plista_thumb.jpg
│ │ │ ├── plista.pdf
│ │ │ ├── relay_media_logo.png
│ │ │ ├── relay_media_thumb.jpg
│ │ │ ├── relay_media.pdf
│ │ │ ├── relaymedia_phone1.png
│ │ │ ├── relaymedia_phone1@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── relaymedia_phone2.png
│ │ │ ├── relaymedia_phone2@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── slate_logo.png
│ │ │ ├── slate_phone1.png
│ │ │ ├── slate_phone1@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── slate_phone2.png
│ │ │ ├── slate_phone2@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── slate_thumb.jpg
│ │ │ ├── slate.pdf
│ │ │ ├── teads_logo.png
│ │ │ ├── teads_logo2.png
│ │ │ ├── teads_phone.png
│ │ │ ├── teads_phone@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── teads_thumb.jpg
│ │ │ ├── teads.pdf
│ │ │ ├── terra_framed1.png
│ │ │ ├── terra_framed2.png
│ │ │ ├── terra_logo.png
│ │ │ ├── terra_thumb.jpg
│ │ │ ├── terra.pdf
│ │ │ ├── wapo_logo.png
│ │ │ ├── wapo_thumb.png
│ │ │ ├── wapo.pdf
│ │ │ ├── washingtonpost_phone.png
│ │ │ ├── washingtonpost_phone@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── wired_logo.png
│ │ │ ├── wired_phone1.png
│ │ │ ├── wired_phone1@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── wired_phone2.png
│ │ │ ├── wired_phone2@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── wired_thumb.jpg
│ │ │ └── wired.pdf
│ │ ├── cheveron-down.svg
│ │ ├── close.svg
│ │ ├── comment.png
│ │ ├── docs
│ │ │ ├── icon_important.svg
│ │ │ ├── icon_note.svg
│ │ │ ├── icon_read.svg
│ │ │ ├── icon_tip.svg
│ │ │ ├── responsive_amp_img.png
│ │ │ ├── too_much_css.png
│ │ │ ├── validator_console_imgerror.png
│ │ │ ├── validator_errors.png
│ │ │ ├── validator_extension_imgerror.png
│ │ │ ├── validator_icon_invalid.png
│ │ │ ├── validator_icon_link.png
│ │ │ ├── validator_icon_valid.png
│ │ │ ├── validator_mandatory_error.png
│ │ │ ├── validator_web_ui.png
│ │ │ └── validator_webui_imgerror.png
│ │ ├── enforce-comment.png
│ │ ├── footer
│ │ │ ├── line-left.png
│ │ │ ├── line-right-2.png
│ │ │ └── line-right.png
│ │ ├── github.png
│ │ ├── hamburger.svg
│ │ ├── home
│ │ │ ├── bg_experience.png
│ │ │ ├── home_hero_phone.png
│ │ │ ├── home_hero_phone@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── home_icon_flexibility.svg
│ │ │ ├── home_icon_performance.svg
│ │ │ ├── home_phone_ebay.png
│ │ │ ├── home_phone_ebay@1_5x.png
│ │ │ ├── [email protected]
│ │ │ ├── lines2.svg
│ │ │ ├── lines3.svg
│ │ │ ├── shapebg.svg
│ │ │ ├── teads_logo.svg
│ │ │ ├── wapo_logo.png
│ │ │ └── wired_logo.png
│ │ ├── ic_open_in_new_black.svg
│ │ ├── ic_open_in_new_white.svg
│ │ ├── icons
│ │ │ ├── 120.png
│ │ │ ├── 144.png
│ │ │ ├── 152.png
│ │ │ ├── 168.png
│ │ │ ├── 180.png
│ │ │ ├── 192.png
│ │ │ ├── 48.png
│ │ │ ├── 512.png
│ │ │ ├── 72.png
│ │ │ ├── 96.png
│ │ │ └── any.svg
│ │ ├── latest
│ │ │ ├── events
│ │ │ │ ├── event_empty.png
│ │ │ │ ├── event_empty.svg
│ │ │ │ └── event_hero.svg
│ │ │ ├── icon_audience.png
│ │ │ ├── icon_audience.svg
│ │ │ ├── icon_calendar.png
│ │ │ ├── icon_calendar.svg
│ │ │ ├── icon_location.png
│ │ │ ├── icon_location.svg
│ │ │ ├── icon_retweet.png
│ │ │ ├── icon_retweet.svg
│ │ │ ├── icon_twitter.svg
│ │ │ ├── latest_hero.jpg
│ │ │ ├── line_hero_back.svg
│ │ │ └── line_hero_front.svg
│ │ ├── liveblog-pagination.png
│ │ ├── login-button.png
│ │ ├── logo-blue.svg
│ │ ├── logout-button.png
│ │ ├── malte.jpg
│ │ ├── motions
│ │ │ └── amp-lines-motions.png
│ │ ├── nav
│ │ │ ├── back_arrow.png
│ │ │ ├── back_arrow.svg
│ │ │ ├── close.png
│ │ │ ├── close.svg
│ │ │ ├── next_level.png
│ │ │ └── next_level.svg
│ │ ├── partners
│ │ │ ├── adobe_analytics.png
│ │ │ ├── chartbeat.png
│ │ │ ├── comscore.png
│ │ │ ├── ggl_bw.png
│ │ │ ├── ggl.png
│ │ │ ├── li.png
│ │ │ ├── nuzzel.png
│ │ │ ├── parsely.png
│ │ │ ├── pinterest.png
│ │ │ ├── tw.png
│ │ │ └── wp.png
│ │ ├── platforms
│ │ │ ├── chrome.png
│ │ │ ├── criteo.png
│ │ │ ├── edge.png
│ │ │ ├── firefox.png
│ │ │ ├── google.png
│ │ │ ├── inmobi.png
│ │ │ ├── kargo.png
│ │ │ ├── mediavine.png
│ │ │ ├── opera.png
│ │ │ ├── plista.png
│ │ │ ├── safari.png
│ │ │ └── yahoo.png
│ │ ├── publishers
│ │ │ ├── abril.png
│ │ │ ├── asahi.png
│ │ │ ├── atlantic_media.png
│ │ │ ├── bbc_news.png
│ │ │ ├── buzzfeed.png
│ │ │ ├── condenast.png
│ │ │ ├── daily_mail.png
│ │ │ ├── economist.png
│ │ │ ├── editora_globo.png
│ │ │ ├── el_pais.png
│ │ │ ├── fairfax_media.png
│ │ │ ├── folha_de_s.paulo.png
│ │ │ ├── franzfurter_allgemeine.png
│ │ │ ├── ft.png
│ │ │ ├── gannett.png
│ │ │ ├── guardian.png
│ │ │ ├── hearst.png
│ │ │ ├── huffington_post.png
│ │ │ ├── la_stampa.png
│ │ │ ├── les_echos.png
│ │ │ ├── mainichi.png
│ │ │ ├── mashable.png
│ │ │ ├── mcclatchy.png
│ │ │ ├── new_york_times.png
│ │ │ ├── newscorp_australia.png
│ │ │ ├── nine_msn.png
│ │ │ ├── nrc.png
│ │ │ ├── ny_daily_news.png
│ │ │ ├── nypost.png
│ │ │ ├── pearson.png
│ │ │ ├── sankei.png
│ │ │ ├── telegraph.png
│ │ │ ├── time.png
│ │ │ ├── uol.png
│ │ │ ├── us_news.png
│ │ │ ├── vox_media.png
│ │ │ ├── wallstreetjournal.png
│ │ │ ├── washington_post.png
│ │ │ └── zeit_online.png
│ │ ├── quotes
│ │ │ ├── chartbeat.jpg
│ │ │ ├── ebay.jpg
│ │ │ ├── faz.jpg
│ │ │ ├── folha.jpg
│ │ │ ├── google.jpg
│ │ │ ├── guardian.jpg
│ │ │ ├── hearst.jpg
│ │ │ ├── lastampa.jpg
│ │ │ ├── newyorktimes.jpeg
│ │ │ ├── twitter.jpg
│ │ │ └── vox.jpg
│ │ ├── return-parameter.png
│ │ ├── sprite.svg
│ │ ├── symbols
│ │ │ ├── carat-down.svg
│ │ │ ├── carat.svg
│ │ │ ├── caret-right.svg
│ │ │ ├── close.svg
│ │ │ ├── lang-icon.svg
│ │ │ ├── logo-blue-standalone.svg
│ │ │ ├── return.svg
│ │ │ ├── search.svg
│ │ │ ├── share-close.svg
│ │ │ ├── share.svg
│ │ │ ├── template.scss
│ │ │ ├── twitter.svg
│ │ │ ├── video-play.svg
│ │ │ └── wordpress.svg
│ │ └── twitter.png
│ ├── manifest.json
│ ├── sass
│ │ ├── _accordions.scss
│ │ ├── _animated_lines.scss
│ │ ├── _animations.scss
│ │ ├── _bg-triangle.scss
│ │ ├── _callouts.scss
│ │ ├── _cards.scss
│ │ ├── _carousel.scss
│ │ ├── _config.scss
│ │ ├── _content-post.scss
│ │ ├── _content-section.scss
│ │ ├── _content.scss
│ │ ├── _doc-nav.scss
│ │ ├── _footer.scss
│ │ ├── _global.scss
│ │ ├── _grid.scss
│ │ ├── _header.scss
│ │ ├── _inline-toc.scss
│ │ ├── _lang_switcher.scss
│ │ ├── _large-cta.scss
│ │ ├── _lightbox.scss
│ │ ├── _mixins.scss
│ │ ├── _nav.scss
│ │ ├── _points.scss
│ │ ├── _post-item.scss
│ │ ├── _responsive.scss
│ │ ├── _search.scss
│ │ ├── _share.scss
│ │ ├── _sidebar.scss
│ │ ├── _sprite_generated.scss
│ │ ├── _sprite.scss
│ │ ├── _syntax_highlighting.scss
│ │ ├── _tables.scss
│ │ ├── _toc.scss
│ │ ├── about-how.min.scss
│ │ ├── about-overview.min.scss
│ │ ├── about-who-vertical.min.scss
│ │ ├── about-who.min.scss
│ │ ├── blog.min.scss
│ │ ├── case-study.min.scss
│ │ ├── design-principles.min.scss
│ │ ├── docs.min.scss
│ │ ├── home.min.scss
│ │ ├── list.min.scss
│ │ ├── main.min.scss
│ │ ├── pages
│ │ │ ├── _about-how.scss
│ │ │ ├── _about-overview.scss
│ │ │ ├── _about-who-vertical.scss
│ │ │ ├── _about-who.scss
│ │ │ ├── _case-study.scss
│ │ │ ├── _design-principles.scss
│ │ │ ├── _events.scss
│ │ │ ├── _faqs.scss
│ │ │ ├── _home.scss
│ │ │ ├── _latest.scss
│ │ │ ├── _list.scss
│ │ │ ├── _post-detail.scss
│ │ │ ├── _roadmap.scss
│ │ │ ├── _who.scss
│ │ │ └── amp-conf.scss
│ │ └── section.min.scss
│ └── video
│ ├── amp-phone.mp4
│ └── amp-phone.webm
├── content
│ ├── contribute
│ │ └── governance.md
│ ├── docs
│ │ ├── _blueprint.yaml
│ │ ├── blank.html
│ │ ├── build.md
│ │ ├── contribute
│ │ │ ├── _blueprint.yaml
│ │ │ ├── contribute.md
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── file-a-bug.md
│ │ │ └── github.md
│ │ ├── contribute.md
│ │ ├── get_started
│ │ │ ├── _blueprint.yaml
│ │ │ ├── create
│ │ │ │ ├── _blueprint.yaml
│ │ │ │ ├── basic_markup.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── basic_markup@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── basic_markup@zh_CN.md
│ │ │ │ ├── include_image.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── include_image@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── include_image@zh_CN.md
│ │ │ │ ├── prepare_for_discovery.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── prepare_for_discovery@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── prepare_for_discovery@zh_CN.md
│ │ │ │ ├── presentation_layout.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── presentation_layout@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── presentation_layout@zh_CN.md
│ │ │ │ ├── preview_and_validate.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── preview_and_validate@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── preview_and_validate@zh_CN.md
│ │ │ │ ├── publish.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── publish@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ └── publish@zh_CN.md
│ │ │ ├── create.md
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── create@pt_BR.md
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── create@zh_CN.md
│ │ │ ├── live_blog.md
│ │ │ ├── [email protected]
│ │ │ ├── login_requiring
│ │ │ │ ├── _blueprint.yaml
│ │ │ │ ├── add_comment.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── login.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── logout.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── summary.md
│ │ │ │ └── [email protected]
│ │ │ ├── login_requiring.md
│ │ │ └── [email protected]
│ │ ├── getting-started.md
│ │ ├── guides
│ │ │ ├── _blueprint.yaml
│ │ │ ├── author_develop
│ │ │ │ ├── _blueprint.yaml
│ │ │ │ ├── ads_on_amp
│ │ │ │ │ ├── _blueprint.yaml
│ │ │ │ │ ├── ads_getting_started.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── ads_tips.md
│ │ │ │ │ └── [email protected]
│ │ │ │ ├── ads_on_amp.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── amp_replacements.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── iframes.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── responsive_amp
│ │ │ │ │ ├── _blueprint.yaml
│ │ │ │ │ ├── art_direction.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── control_layout.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── control_layout@pt_BR.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── control_layout@zh_CN.md
│ │ │ │ │ ├── custom_fonts.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── placeholders.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── style_pages.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── style_pages@pt_BR.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ └── style_pages@zh_CN.md
│ │ │ │ ├── responsive_amp.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── responsive_amp@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── responsive_amp@zh_CN.md
│ │ │ │ ├── third_party_components.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── third_party_components@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ └── third_party_components@zh_CN.md
│ │ │ ├── author_develop.md
│ │ │ ├── debug
│ │ │ │ ├── _blueprint.yaml
│ │ │ │ ├── validate.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── validate@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ └── validate@zh_CN.md
│ │ │ ├── debug.md
│ │ │ ├── deploy
│ │ │ │ ├── _blueprint.yaml
│ │ │ │ ├── analytics_amp
│ │ │ │ │ ├── _blueprint.yaml
│ │ │ │ │ ├── analytics_basics.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── analytics_basics@pt_BR.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── analytics_basics@zh_CN.md
│ │ │ │ │ ├── deep_dive_analytics.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── deep_dive_analytics@pt_BR.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── deep_dive_analytics@zh_CN.md
│ │ │ │ │ ├── use_cases.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── use_cases@pt_BR.md
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ ├── [email protected]
│ │ │ │ │ └── use_cases@zh_CN.md
│ │ │ │ ├── analytics_amp.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── analytics_amp@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── analytics_amp@zh_CN.md
│ │ │ │ ├── discovery.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── discovery@pt_BR.md
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── [email protected]
│ │ │ │ ├── discovery@zh_CN.md
│ │ │ │ ├── engagement.md
│ │ │ │ └── [email protected]
│ │ │ ├── deploy.md
│ │ │ └── embed
│ │ │ ├── _blueprint.yaml
│ │ │ └── login-paywalls.md
│ │ ├── guides.md
│ │ ├── reference
│ │ │ ├── _blueprint.yaml
│ │ │ ├── common_attributes.md
│ │ │ ├── components
│ │ │ │ ├── _blueprint.yaml
│ │ │ │ ├── ads-analytics
│ │ │ │ │ └── _blueprint.yaml
│ │ │ │ ├── dynamic-content
│ │ │ │ │ └── _blueprint.yaml
│ │ │ │ ├── layout
│ │ │ │ │ └── _blueprint.yaml
│ │ │ │ ├── media
│ │ │ │ │ └── _blueprint.yaml
│ │ │ │ ├── presentation
│ │ │ │ │ └── _blueprint.yaml
│ │ │ │ └── social
│ │ │ │ └── _blueprint.yaml
│ │ │ ├── components.md
│ │ │ ├── experimental.md
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── experimental@pt_BR.md
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── experimental@zh_CN.md
│ │ │ ├── validation_errors.md
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── validation_errors@pt_BR.md
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ ├── [email protected]
│ │ │ └── validation_errors@zh_CN.md
│ │ ├── reference.md
│ │ └── tutorials.md
│ ├── includes
│ │ ├── _blueprint.yaml
│ │ ├── amp-conf-2017.yaml
│ │ ├── amp-iframe.md
│ │ ├── blog_feed.yaml
│ │ ├── doc.yaml
│ │ ├── events.yaml
│ │ ├── home.yaml
│ │ ├── html-example.md
│ │ ├── latest.yaml
│ │ ├── list-blog.yaml
│ │ ├── lists.yaml
│ │ ├── menu.yaml
│ │ ├── roadmap.yaml
│ │ └── tweets.yaml
│ ├── latest
│ │ ├── _blueprint.yaml
│ │ ├── blog
│ │ │ ├── _blueprint.yaml
│ │ │ ├── 1056.md
│ │ │ ├── ads-on-the-web-will-get-better-with-amp-heres-how.md
│ │ │ ├── amp-roadmap-update-for-mid-q1-2017.md
│ │ │ ├── amp-up-for-amp-conf-2017.md
│ │ │ ├── grow-your-business-with-ads-on-amp.md
│ │ │ ├── new-default-placeholders-for-ads-in-amp.md
│ │ │ ├── new-industry-benchmarks-for-mobile-page-speed.md
│ │ │ ├── speeding-up-news-apps-with-amp.md
│ │ │ ├── whats-in-an-amp-url.md
│ │ │ └── why-amp-caches-exist.md
│ │ ├── latest.html
│ │ ├── list-blog.html
│ │ ├── list-event.html
│ │ ├── list-past-event.html
│ │ └── roadmap.html
│ ├── learn
│ │ ├── _blueprint.yaml
│ │ ├── about-amp.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── about-amp@pt_BR.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── about-amp@zh_CN.md
│ │ ├── about-how.yaml
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── about-how@pt_BR.yaml
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── about-how@zh_CN.yaml
│ │ ├── amp-design-principles.yaml
│ │ ├── browsers.md
│ │ ├── case-studies
│ │ │ ├── _blueprint.yaml
│ │ │ ├── category
│ │ │ │ ├── _blueprint.yaml
│ │ │ │ ├── advertisers.md
│ │ │ │ └── publishers.md
│ │ │ ├── gizmodo.md
│ │ │ ├── hearst.md
│ │ │ ├── milestone.md
│ │ │ ├── plista.md
│ │ │ ├── relay_media.md
│ │ │ ├── slate.md
│ │ │ ├── teads.md
│ │ │ ├── terra.md
│ │ │ ├── washingtonpost.md
│ │ │ └── wired.md
│ │ ├── case-studies.html
│ │ ├── how-amp-works.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── how-amp-works@pt_BR.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── how-amp-works@zh_CN.md
│ │ ├── metrics.html
│ │ ├── overview.yaml
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── overview@pt_BR.yaml
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── overview@zh_CN.yaml
│ │ ├── who
│ │ │ ├── _blueprint.yaml
│ │ │ ├── ad-tech-platforms.yaml
│ │ │ ├── advertisers.yaml
│ │ │ ├── amp-ads.yaml
│ │ │ └── publishers.yaml
│ │ └── who-uses-amp.yaml
│ ├── pages
│ │ ├── _blueprint.yaml
│ │ ├── amp-conf-2017
│ │ │ ├── _blueprint.yaml
│ │ │ ├── accessibility.html
│ │ │ └── code-of-conduct.html
│ │ ├── amp-conf-2017.html
│ │ ├── home.html
│ │ ├── how-it-works.html
│ │ └── metrics_chart.html
│ └── support
│ ├── _blueprint.yaml
│ ├── developer
│ │ ├── _blueprint.yaml
│ │ ├── documentation-bug.md
│ │ ├── mailing-list.md
│ │ ├── platform-bug.md
│ │ ├── slack.md
│ │ └── stack-overflow.md
│ ├── developer.md
│ ├── faqs
│ │ ├── _blueprint.yaml
│ │ ├── overview.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── overview@pt_BR.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── overview@zh_CN.md
│ │ ├── platform-involvement.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── platform-involvement@pt_BR.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── platform-involvement@zh_CN.md
│ │ ├── publisher-monetization.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── publisher-monetization@pt_BR.md
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── publisher-monetization@zh_CN.md
│ │ └── supported-platforms.md
│ ├── faqs.md
│ ├── platform.md
│ ├── support.md
│ ├── vendor
│ │ ├── _blueprint.yaml
│ │ └── amp-certification.md
│ └── vendor.md
├── CONTRIBUTING.md
├── firebase.json
├── gulpfile.js
├── LICENSE
├── npm-shrinkwrap.json
├── package.json
├── podspec.yaml
├── pwa
│ ├── google7199ce9da1ad191b.html
│ ├── pwa.html
│ ├── pwa.js
│ └── service-worker.js
├── README.md
├── scripts
│ ├── component_categories.json
│ ├── import_docs.js
│ ├── import_docs.json
│ ├── update_blog_links.js
│ ├── update_platforms_page.js
│ └── update_tweets.js
├── translations
│ ├── ar
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── de
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── es
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── fr
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── id
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── it
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── ja
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── ko
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── messages.pot
│ ├── pl
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── pt_BR
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── ru
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── th
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ ├── tr
│ │ └── LC_MESSAGES
│ │ └── messages.po
│ └── zh_CN
│ └── LC_MESSAGES
│ └── messages.po
└── views
├── about-casestudies.html
├── about-how.html
├── about-overview.html
├── about-who-vertical.html
├── about-who.html
├── base.html
├── blank.html
├── blog_detail.html
├── case-study.html
├── design-principles.html
├── doc.html
├── grid_page.html
├── list_page.html
├── partials
│ ├── breadcrumb-nav.html
│ ├── doc_nav.html
│ ├── faq-accordion.html
│ ├── footer-cta.html
│ ├── footer.html
│ ├── grid-card.html
│ ├── head.html
│ ├── header.html
│ ├── lang_switcher.html
│ ├── large-cta.html
│ ├── lines.html
│ ├── nav.html
│ ├── points.html
│ ├── post-item.html
│ ├── promo_banner.html
│ ├── search.html
│ ├── share.html
│ ├── sidebar.html
│ └── sub_nav.html
└── section_page.html
```
# Files
--------------------------------------------------------------------------------
/content/docs/guides/deploy/analytics_amp/deep_dive_analytics@pt_BR.md:
--------------------------------------------------------------------------------
```markdown
---
$title: Informações detalhadas sobre o AMP Analytics
toc: true
---
[TOC]
Este guia fornece informações detalhadas sobre o
[componente amp-analytics](/docs/reference/extended/amp-analytics.html),
dividindo uma configuração de exemplo do `amp-analytics` nestas três categorias básicas:
O restante deste guia usa esse exemplo de configuração,
que rastreia as visualizações de páginas e os cliques de usuários em links
e envia os dados de análise ao provedor de terceiros,
[Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/):
[sourcecode:html]
<amp-analytics type="googleanalytics" config="https://example.com/analytics.account.config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
},
"vars": {
"account": "ABC123"
},
"extraUrlParams": {
"cd1": "AMP"
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
},
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
}
</script>
</amp-analytics>
[/sourcecode]
**Observação:** o exemplo de código acima tem por objetivo ajudá-lo a aprender, mas não é de forma alguma um exemplo realista. Se você estiver trabalhando com provedores de análise, é provável que o exemplo acima não faça sentido; as configurações dos provedores removem a complexidade. Consulte a documentação do seu provedor de análises para obter exemplos de configurações.
## Onde enviar dados de análise: atributo type
O AMP foi projetado para oferecer suporte a dois padrões comuns de coleta de dados:
* Ingestão por um endpoint de propriedade do editor para sistemas de análise internos.
* Ingestão por um endpoint de propriedade de um fornecedor para interoperabilidade com uma solução desse fornecedor
(por exemplo, [Adobe Analytics](https://helpx.adobe.com/marketing-cloud/analytics.html), [Chartbeat](http://support.chartbeat.com/docs/), [Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/)).
Para enviar dados de análise a um provedor de análises,
inclua o atributo `type` na tag `amp-analytics` e defina seu valor
para o fornecedor adequado, segundo definido na
[especificação do amp-analytics](/docs/reference/extended/amp-analytics.html).
Por exemplo: `<amp-analytics type="googleanalytics">` envia dados de análise
ao provedor de análise de terceiros, Google Analytics.
Para enviar dados para um endpoint de propriedade do editor,
basta não incluir o atributo `type`;
os dados de análise são enviados para endpoints definidos para cada
[solicitação](/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute).
As configurações de fornecedores de análises são uma forma rápida
de dar os primeiros passos com o `amp-analytics`.
Você deve consultar a documentação e os recursos de ajuda
do fornecedor para obter mais orientações.
Como mencionado anteriormente,
a lista de fornecedores que já foram integrados ao AMP, assim como os links
para suas documentações específicas, pode ser encontrada na
[especificação do amp-analytics](/docs/reference/extended/amp-analytics.html).
Se você é um fornecedor de análises,
saiba mais sobre
[como integrar sua própria configuração de análise no AMP HTML](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/integrating-analytics.md).
## Carregar configuração remota: atributo config
Você não precisa incluir toda a configuração
para `amp-analytics` inteiramente na sua página AMP.
Em vez disso, você pode chamar um URL remoto
para toda a configuração ou parte dela.
Isso permite que você faça coisas como variar a configuração
com base em uma solicitação específica.
Se você, como editor, tem controle sobre o arquivo remoto,
é possível realizar qualquer procedimento necessário no lado do servidor
para construir os dados de configuração.
O primeiro passo para carregar configurações remotas é
incluir o atributo config na tag `amp-analytics`:
[sourcecode:html]
<amp-analytics config="https://example.com/analytics.account.config.json">
[/sourcecode]
O próximo passo é criar o conteúdo JSON que reside no URL remoto.
Neste exemplo simples,
a configuração contida no objeto JSON é exatamente o valor da variável para a conta de análise.
Conteúdo de exemplo em `https://example.com/analytics.account.config.json`:
[sourcecode:html]
{
"vars": {
"account": "UA-XXXXX-Y" // Replace with your property ID.
}
}
[/sourcecode]
A etapa final é assegurar-se de que o arquivo remoto tenha sido extraído
para o lugar adequado na configuração do `amp-analytics`.
Nas duas solicitações de `pageview` e `event` do exemplo,
o valor da variável `account` é definido automaticamente
para o valor de conta no URL remoto (`"account": "UA-XXXXX-Y"`):
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
**Importante:** o AMP não realiza a validação em relação a diversos usos da mesma variável.
Os valores são preenchidos seguindo uma ordem de preferência de substituição de variável
e os valores nos URLs remotos estão no topo dessa ordem
(consulte [Ordem de substituição de variáveis](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
## Solicitações, acionamento e transportes
O atributo `requests` define “quais dados são enviados”
(por exemplo, `pageviews`, `events`),
e para onde os dados são enviados (os URLs usados para transmitir dados).
O atributo `triggers` descreve quando dados de análise devem ser enviados,
por exemplo, quando um usuário visualiza uma página ou clica em um link.
O atributo `transport` especifica como enviar a solicitação,
mais especificamente, o protocolo.
Continue lendo para saber mais sobre essas configurações.
(Você também pode ler sobre essas configurações na
[referência do amp-analytics](/docs/reference/extended/amp-analytics.html).)
### Quais dados são enviados: atributo requests
O `request-name` é usado na configuração de acionamento para especificar
que solicitação deve ser enviada em resposta a um evento específico.
O `request-value` é um URL `https`.
Esses valores podem incluir tokens de marcadores de posição
que podem fazer referência a outras solicitações ou variáveis.
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
Alguns provedores de análise (incluindo o Google Analytics)
já forneceram configurações,
que você usará por meio do atributo `type`.
Se você estiver usando um provedor de análises,
pode ser que não precise incluir informações de `requests`.
Consulte a documentação do seu fornecedor para descobrir
se `requests` precisa ser configurado, e como.
#### Anexar o URL de solicitação: parâmetros de URL adicionais
O atributo [extraUrlParams](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/amp-analytics.md#extra-url-params)
especifica parâmetros adicionais para anexar à string de consulta do URL da solicitação por meio da convenção habitual "&foo=baz".
O exemplo `amp-analytics` adiciona um parâmetro adicional <code>cd1</code>
à solicitação e define o valor do parâmetro para “AMP”:
[sourcecode:html]
"extraUrlParams": {
"cd1": "AMP"
}
[/sourcecode]
### Quando os dados são enviados: atributo trigger
O atributo `triggers` descreve quando uma solicitação de análise deve ser enviada.
Ele contém um par de valores-chave de trigger-name e trigger-configuration.
O nome do trigger pode ser qualquer string composta
por caracteres alfanuméricos (a-zA-Z0-9).
Por exemplo,
o seguinte elemento `amp-analytics` está configurado para enviar uma solicitação para
`https://example.com/analytics` quando o documento for carregado pela primeira vez,
e cada vez que uma tag `a` for clicada:
[sourcecode:html]
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
}
[/sourcecode]
O AMP oferece suporte às seguintes configurações de acionamento:
<table>
<thead>
<tr>
<th data-th="Trigger Config" class="col-thirty">Configuração de acionamento</th>
<th data-th="Description">Descrição</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Trigger Config"><code>on</code> (obrigatório)</td>
<td data-th="Description">O evento a ouvir. Os valores válidos são <code>click</code>, <code>scroll</code>, <code>timer</code> e <code>visible</code>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>request</code> (obrigatório)</td>
<td data-th="Description">Nome da solicitação a enviar (segundo especificado nas <a href="/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute">solicitações</a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>vars</code></td>
<td data-th="Description">Um objeto que contém pares de valor-chave usados para modificar<code>vars</code> definidas na configuração de nível superior ou para especificar <code>vars</code> exclusivas para esse acionamento (consulte também <a href="/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering">Ordem da substituição de variáveis</a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>selector</code> (obrigatório quando <code>on</code> for definido como <code>click</code>)</td>
<td data-th="Description">Um seletor CSS usado para refinar quais elementos devem ser rastreados. Use o valor <code>*</code> para rastrear todos os elementos. Essa configuração é usada em conjunto com o acionamento <code>click</code>. Saiba como usar o seletor para <a href="/docs/guides/analytics/use_cases.html#tracking-page-clicks">rastrear cliques de página</a> e <a href="/docs/guides/analytics/use_cases.html#tracking-social-interactions">interações sociais</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>scrollSpec</code> (obrigatório quando <code>on</code> for definido como <code>scroll</code>)</td>
<td data-th="Description">Controla sob que condições o evento <code>scroll</code> é acionado quando a página é rolada. Esse objeto pode conter<code>verticalBoundaries</code> e <code>horizontalBoundaries</code>. Pelo menos uma das duas propriedades é obrigatória para que um evento <code>scroll</code> seja acionado. Os valores para ambas as propriedades devem ser matrizes de números que contenham os limites nos quais um evento de rolagem é gerado. Consulte exemplos em <a href="/docs/guides/analytics/use_cases.html#tracking-scrolling">rastrear rolagem</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>timerSpec</code> (obrigatório quando <code>on</code> for definido como <code>timer</code>)</td>
<td data-th="Description">Controla quando o evento <code>timer</code> é acionado. O temporizador será acionado imediatamente e, depois, a um intervalo especificado. Essa configuração é usada em conjunto com o acionamento <code>timer</code>.</td>
</tr>
</tbody>
</table>
**Importante:** acionamentos de uma configuração com menor precedência são sobrepostos
por acionamentos com os mesmos nomes de uma configuração com maior precedência.
(consulte [Ordem de substituição de variáveis](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
### Como os dados são enviados: atributo transport
O atributo `transport` especifica como enviar a solicitação.
Os três seguintes métodos são ativados por padrão:
<table>
<thead>
<tr>
<th data-th="Transport Method" class="col-thirty">Método de transporte</th>
<th data-th="Description">Descrição</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Transport Method"><code>beacon</code></td>
<td data-th="Description">Indica que <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a> pode ser usado para transmitir a solicitação. Isso enviará uma solicitação de <code>POST</code> com credenciais e o corpo vazio.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>xhrpost</code></td>
<td data-th="Description">Indica que <code>XMLHttpRequest</code> pode ser usado para transmitir a solicitação. Isso enviará uma solicitação de <code>POST</code> com credenciais e corpo vazio.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>image</code></td>
<td data-th="Description">Indica que a solicitação pode ser enviada gerando uma tag <code>Image</code>. Isso enviará uma solicitação <code>GET</code>.</td>
</tr>
</tbody>
</table>
Somente um método de transporte é usado:
aquele com a precedência mais alta
que esteja ativado, autorizado e disponível.
A precedência é `beacon` > `xhrpost` > `image`.
Se o user agent do cliente não oferecer suporte a um método,
o próximo método de precedência mais alta ativado será usado.
Somente inclua o atributo `transport` em sua configuração
se quiser limitar as opções de transporte,
caso contrário, você poderá interromper as solicitações.
No exemplo abaixo,
`beacon` e `xhrpost` são definidos como falsos,
de forma que não serão usados, mesmo que tenham precedência mais alta do que `image`.
Se o user agent do cliente oferecer suporte ao método `image`,
ele será usado; caso contrário, a solicitação não será enviada.
[sourcecode:html]
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
[/sourcecode]
## Ordem de substituição de variáveis
O AMP preenche as variáveis com valores em uma ordem de precedência:
1. Configurações remotas (via `config`).
2. `vars` aninhadas em um acionamento dentro de `triggers`.
3. `vars` no nível superior aninhadas dentro de `amp-analytics`.
4. Valores fornecidos pela plataforma.
Neste exemplo, há uma configuração remota,
variáveis definidas no nível superior, em acionamentos e no nível de plataforma:
[sourcecode:html]
<amp-analytics config="http://example.com/config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}&clientId=${clientId(cid-scope)}",
},
"vars": {
"account": "ABC123",
"title": "Homepage"
},
"triggers": {
"some-event": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "My homepage",
"clientId": "my user"
}
}
}
</script>
</amp-analytics>
[/sourcecode]
Quando a mesma `var` é definida em vários locais,
a ordem de precedência da variável define seu valor uma vez.
Assim, se a configuração remota definiu `account` como UA-XXXXX-Y no exemplo acima,
os valores de várias variáveis serão os seguintes:
<table>
<thead>
<tr>
<th data-th="var" class="col-thirty"><code>var</code></th>
<th data-th="Value">Valor</th>
<th data-th="Defined By" class="col-thirty">Definido por</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="var"><code>canonicalUrl</code></td>
<td data-th="Value"><code>http://example.com/path/to/the/page</code></td>
<td data-th="Defined By">Plataforma</td>
</tr>
<tr>
<td data-th="var"><code>title</code></td>
<td data-th="Value">My homepage</td>
<td data-th="Defined By">Acionamento</td>
</tr>
<tr>
<td data-th="var"><code>account</code></td>
<td data-th="Value"><code>UA-XXXXX-Y</code></td>
<td data-th="Defined By">Configurações remotas</td>
</tr>
<tr>
<td data-th="var"><code>clientId</code></td>
<td data-th="Value">my user</td>
<td data-th="Defined By">Acionamento</td>
</tr>
</tbody>
</table>
```
--------------------------------------------------------------------------------
/content/docs/guides/deploy/analytics_amp/[email protected]:
--------------------------------------------------------------------------------
```markdown
---
$title: Więcej o analityce AMP
toc: true
---
[TOC]
Ten przewodnik zawiera szczegółowe omówienie
[komponentu amp-analytics](/docs/reference/extended/amp-analytics.html),
dzieląc przykładową konfigurację z elementem `amp-analytics` na następujące kluczowe bloki:
Podstawą przewodnika jest przykładowa konfiguracja,
która monitoruje wyświetlenia strony i kliknięcia linków przez użytkownika
oraz wysyła dane analityczne do niezależnego dostawcy
[Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/):
[sourcecode:html]
<amp-analytics type="googleanalytics" config="https://example.com/analytics.account.config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
},
"vars": {
"account": "ABC123"
},
"extraUrlParams": {
"cd1": "AMP"
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
},
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
}
</script>
</amp-analytics>
[/sourcecode]
**Uwaga:** Powyższy kod przykładowy ma za zadanie pomoc w nauce, ale nie jest on w żadnym razie przykładem realistycznym. W przypadku współpracy z dostawcami usług analitycznych prawdopodobne jest, że powyższy przykład nie ma sensu; konfiguracje dostawców eliminują złożoność. Sprawdź informacje na temat przykładowych konfiguracji w dokumentacji dostawcy.
## Gdzie wysyłać dane analityczne: atrybut type
AMP zaprojektowano do obsługi dwóch typowych wzorców gromadzenia danych:
* Przyswajanie w należącym do wydawcy punkcie końcowym na potrzeby wewnętrznych systemów analitycznych.
* Przyswajanie w punkcie końcowym należącym do dostawcy w celu zapewnienia współdziałania z rozwiązaniem dostawcy
(na przykład [Adobe Analytics](https://helpx.adobe.com/marketing-cloud/analytics.html), [Chartbeat](http://support.chartbeat.com/docs/), [Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/)).
W celu wysłania danych analitycznych do dostawcy usług analitycznych
dołącz atrybut `type` w znaczniku `amp-analytics` i ustaw jego wartość,
aby odpowiadała konkretnemu dostawcy, zgodnie z definicją w
[specyfikacji elementu amp-analytics](/docs/reference/extended/amp-analytics.html).
Na przykład element `<amp-analytics type="googleanalytics">` wysyła dane analityczne
do niezależnego dostawcy usług analitycznych Google Analytics.
Aby wysłać dane do punktu końcowego należącego do wydawcy,
wystarczy po prostu nie dołączać atrybutu `type`;
dane analityczne będą wysyłane do punktów końcowych zdefiniowanych dla każdego
[żądania](/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute).
Konfiguracje dostawców usług analitycznych stanowią szybką metodę
rozpoczęcia korzystania z elementu `amp-analytics`.
Dodatkowych informacji należy szukać w dokumentacji dostawcy
i zasobach pomocy.
Jak wspomniano wcześniej,
listę dostawców, którzy już zintegrowali swoje systemy z AMP, a także linki
do ich dokumentacji, można znaleźć w
[specyfikacji elementu amp-analytics](/docs/reference/extended/amp-analytics.html).
Dostawcy usług analitycznych mogą
dowiedzieć się więcej o
[integracji własnej konfiguracji analitycznej z AMP HTML](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/integrating-analytics.md).
## Ładowanie konfiguracji zdalnej: atrybut config
Nie ma potrzeby dołączania całej konfiguracji
elementu `amp-analytics` na stronie AMP.
Zamiast tego można wywołać zdalny adres URL
z całą konfiguracją lub jej częścią.
Umożliwia to na przykład zmienianie konfiguracji
w zależności od konkretnego żądania.
Jeśli jesteś wydawcą i masz kontrolę nad plikiem zdalnym,
możesz wykonać dowolne przetwarzanie po stronie serwera niezbędne
do skonstruowania danych konfiguracji.
Pierwszy krok do załadowania zdalnych konfiguracji
to dołączenie atrybutu config do znacznika `amp-analytics`:
[sourcecode:html]
<amp-analytics config="https://example.com/analytics.account.config.json">
[/sourcecode]
Następny krok to utworzenie treści JSON funkcjonującej pod zdalnym adresem URL.
W tym prostym przykładzie
konfiguracja zawarta w obiekcie JSON to tylko wartość zmiennej dla konta analitycznego.
Przykładowa treść w obiekcie `https://example.com/analytics.account.config.json`:
[sourcecode:html]
{
"vars": {
"account": "UA-XXXXX-Y" // Replace with your property ID.
}
}
[/sourcecode]
Ostatni krok to upewnienie się, które dane z pliku zdalnego są wyciągane
do odpowiedniego miejsca w konfiguracji elementu `amp-analytics`.
W obu żądaniach `pageview` i `event`
wartości zmiennej`account` jest automatycznie nadawana
wartość konta w zdalnym adresie URL (`"account": "UA-XXXXX-Y"`):
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
**Ważne:** AMP nie sprawdza poprawności dla wielu wystąpień tej samej zmiennej.
Wartości są zapełniane zgodnie z preferowaną kolejnością podstawiania zmiennych,
a wartości w zdalnych adresach URL są na początku tej kolejności
(zobacz [Kolejność podstawiania zmiennych](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
## Żądania, wyzwalacze i transporty
Atrybut `requests` definiuje wysyłane dane
(na przykład `pageviews`, `events`)
oraz miejsce docelowe dla wysyłanych danych (adresy URL używane do transmisji danych).
Atrybut `triggers` określa moment wysłania danych analitycznych,
na przykład kiedy użytkownik wyświetli stronę lub kiedy kliknie link.
Atrybut `transport` określa sposób wysłania żądania,
a dokładniej — protokół.
Czytaj dalej, aby dowiedzieć się więcej o tych konfiguracjach.
(O tych konfiguracjach możesz także przeczytać w części
[Informacje uzupełniające o elemencie amp-analytics](/docs/reference/extended/amp-analytics.html).)
### Dane do wysłania: atrybut requests
Atrybut `request-name` jest używany w konfiguracji wyzwalania do określania,
które żądanie powinno zostać wysłane w odpowiedzi na konkretne zdarzenie.
Atrybut `request-value` to adres URL w protokole `https`.
Te wartości mogą zawierać tokeny zmiennej,
które mogą odwoływać się do innych żądań lub zmiennych.
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
Niektórzy dostawcy usług analitycznych (w tym Google Analytics)
już udostępnili konfigurację,
której używa się za pośrednictwem atrybutu `type`.
W przypadku korzystania z dostawcy usług analitycznych
dołączanie informacji `requests` może nie być konieczne.
Informacje o tym, czy konfigurowanie atrybutu
`requests` jest konieczne, można znaleźć w dokumentacji dostawcy.
#### Dołączanie adresu URL żądania: Dodatkowe parametry adresu URL
Atrybut [extraUrlParams](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/amp-analytics.md#extra-url-params)
określa dodatkowe parametry dołączane do ciągu znaków zapytania adresu URL żądania przy użyciu zwykłej konwencji „&foo=baz”.
Przykład z elementem `amp-analytics` wprowadza dodatkowy parametr <code>cd1</code>
w żądaniu i nadaje mu wartość „AMP”:
[sourcecode:html]
"extraUrlParams": {
"cd1": "AMP"
}
[/sourcecode]
### Moment wysłania danych: atrybut triggers
Atrybut `triggers` określa moment, w którym ma zostać wysłane żądanie analityczne.
Zawiera on parę klucz-wartość z nazwą wyzwalacza i konfiguracją wyzwalacza.
Nazwa wyzwalacza może być dowolnym łańcuchem
znaków alfanumerycznych (a-z A-Z 0-9).
Na przykład
następujący element `amp-analytics` jest skonfigurowany do wysyłania żądania na adres
`https://example.com/analytics`, kiedy dokument jest ładowany po raz pierwszy,
i za każdym razem, kiedy zostanie kliknięty znacznik `a`:
[sourcecode:html]
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
}
[/sourcecode]
AMP obsługuje następujące konfiguracje wyzwalacza:
<table>
<thead>
<tr>
<th data-th="Trigger Config" class="col-thirty">Konfiguracja wyzwalacza</th>
<th data-th="Description">Opis</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Trigger Config"><code>on</code> (wymagane)</td>
<td data-th="Description">Nasłuchiwane zdarzenie. Poprawne wartości to <code>click</code>, <code>scroll</code>, <code>timer</code> i <code>visible</code>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>request</code> (wymagane)</td>
<td data-th="Description">Nazwa żądania do wysłania (określona atrybutem <a href="/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute">requests</a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>vars</code></td>
<td data-th="Description">Obiekt zawierający pary klucz-wartość używany do zastąpienia deklaracji <code>vars</code> w konfiguracji najwyższego poziomu lub do określenia deklaracji <code>vars</code> właściwej tylko dla tego wyzwalacza (zobacz też <a href="/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering">Kolejność podstawiania zmiennych</a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>selector</code> (wymagane, gdy parametr <code>on</code> ma wartość <code>click</code>)</td>
<td data-th="Description">Selektor CSS używany do precyzowania elementów, które mają być monitorowane. Użyj wartości <code>*</code>, aby monitorować wszystkie elementy. Ta konfiguracja jest używana w połączeniu z wyzwalaczem <code>click</code>. Dowiedz się, jak używać selektora do <a href="/docs/guides/analytics/use_cases.html#tracking-page-clicks">monitorowania kliknięć na stronie</a> oraz <a href="/docs/guides/analytics/use_cases.html#tracking-social-interactions">interakcji społecznościowych</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>scrollSpec</code> (wymagane, gdy parametr <code>on</code> ma wartość <code>scroll</code>)</td>
<td data-th="Description">Steruje okolicznościami wyzwolenia zdarzenia <code>scroll</code> podczas przewijania strony. Ten obiekt może zawierać właściwości <code>verticalBoundaries</code> i <code>horizontalBoundaries</code>. Co najmniej jedna z nich jest wymagana do wyzwolenia zdarzenia <code>scroll</code>. Wartości obydwu właściwości powinny być tablicami liczb zawierającymi granice, po przekroczeniu których generowane jest zdarzenie przewijania. Zobacz przykład dotyczący <a href="/docs/guides/analytics/use_cases.html#tracking-scrolling">monitorowania przewijania</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>timerSpec</code> (wymagane, gdy parametr <code>on</code> ma wartość <code>timer</code>)</td>
<td data-th="Description">Steruje momentem wyzwolenia zdarzenia <code>timer</code>. Licznik czasu zostanie wyzwolony natychmiast, a następnie będzie wyzwalany z określonym interwałem. Ta konfiguracja jest używana w połączeniu z wyzwalaczem <code>timer</code>.</td>
</tr>
</tbody>
</table>
**Ważne:** Wyzwalacze z konfiguracji o niższym priorytecie są przesłaniane
przez wyzwalacze o tych samych nazwach z konfiguracji o wyższym priorytecie
(zobacz [Kolejność podstawiania zmiennych](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
### Sposób wysyłania danych: atrybut transport
Atrybut `transport` określa sposób wysłania żądania.
Domyślnie są włączone trzy następujące metody:
<table>
<thead>
<tr>
<th data-th="Transport Method" class="col-thirty">Metoda transportu</th>
<th data-th="Description">Opis</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Transport Method"><code>beacon</code></td>
<td data-th="Description">Wskazuje możliwość użycia metody <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a> do transmisji żądania. Spowoduje to wysłanie żądania <code>POST</code> z danymi logowania i pustą treścią.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>xhrpost</code></td>
<td data-th="Description">Wskazuje możliwość użycia żądania <code>XMLHttpRequest</code> do transmisji żądania. Spowoduje to wysłanie żądania <code>POST</code> z danymi logowania i pustą treścią.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>image</code></td>
<td data-th="Description">Wskazuje możliwość wysłania żądania przez wygenerowanie znacznika <code>Image</code>. Spowoduje to wysłanie żądania <code>GET</code>.</td>
</tr>
</tbody>
</table>
Używana jest tylko jedna metoda transportu:
ta z najwyższym priorytetem
, która jest włączona, dozwolona i dostępna.
Priorytet jest następujący `beacon` > `xhrpost` > `image`.
Jeśli agent użytkownika klienta nie obsługuje metody,
używana jest następna włączona metoda o najwyższym priorytecie.
Atrybut `transport` należy dołączać do swojej konfiguracji
tylko wtedy, gdy chce się ograniczyć opcje transportu,
w przeciwnym razie można zatrzymać żądania.
W przykładzie powyżej
metody `beacon` i `xhrpost` mają wartość false,
więc nie będą używane, pomimo że mają wyższy priorytet niż metoda `image`.
Jeśli agent użytkownika klienta obsługuje metodę `image`,
zostanie ona użyta. W przeciwnym razie żadne żądanie nie zostanie wysłane.
[sourcecode:html]
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
[/sourcecode]
## Kolejność podstawiania zmiennych
AMP podstawia wartości za zmienne w następującej kolejności:
1. Konfiguracje zdalne (atrybut `config`).
2. Deklaracje `vars` zagnieżdżone wewnątrz wyzwalacza w atrybucie `triggers`.
3. Deklaracje `vars` na najwyższym poziomie zagnieżdżone w elemencie `amp-analytics`.
4. Wartości podane przez platformę.
W tym przykładzie występuje konfiguracja zdalna,
zmienne zdefiniowane na najwyższym poziomie, w wyzwalaczach i na poziomie platformy:
[sourcecode:html]
<amp-analytics config="http://example.com/config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}&clientId=${clientId(cid-scope)}",
},
"vars": {
"account": "ABC123",
"title": "Homepage"
},
"triggers": {
"some-event": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "My homepage",
"clientId": "my user"
}
}
}
</script>
</amp-analytics>
[/sourcecode]
Gdy ten sam element `var` jest zdefiniowany w wielu miejscach,
pierwszeństwo zmiennych powoduje, że jego wartość jest ustawiana tylko raz.
Oznacza to, że jeśli w konfiguracji zdalnej element `account` zdefiniowano jako UA-XXXXX-Y w przykładzie powyżej,
wartości różnych elementów var będą następujące:
<table>
<thead>
<tr>
<th data-th="var" class="col-thirty"><code>var</code></th>
<th data-th="Value">Wartość</th>
<th data-th="Defined By" class="col-thirty">Definiowana przez</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="var"><code>canonicalUrl</code></td>
<td data-th="Value"><code>http://example.com/path/to/the/page</code></td>
<td data-th="Defined By">Platforma</td>
</tr>
<tr>
<td data-th="var"><code>title</code></td>
<td data-th="Value">My homepage</td>
<td data-th="Defined By">Wyzwalacz</td>
</tr>
<tr>
<td data-th="var"><code>account</code></td>
<td data-th="Value"><code>UA-XXXXX-Y</code></td>
<td data-th="Defined By">Konfiguracja zdalna</td>
</tr>
<tr>
<td data-th="var"><code>clientId</code></td>
<td data-th="Value">my user</td>
<td data-th="Defined By">Wyzwalacz</td>
</tr>
</tbody>
</table>
```
--------------------------------------------------------------------------------
/content/docs/guides/deploy/analytics_amp/[email protected]:
--------------------------------------------------------------------------------
```markdown
---
$title: Análisis profundo de AMP Analytics
toc: true
---
[TOC]
En esta guía se analiza en detalle el
[componente amp-analytics](/docs/reference/extended/amp-analytics.html)
a través del desglose de una configuración de `amp-analytics` de ejemplo en los siguientes componentes fundamentales:
En el resto de la guía se usa esta configuración de ejemplo,
con la cual se realiza un seguimiento de las vistas de página y los clics de los usuario en diferentes vínculos,
y se envían los datos del análisis al proveedor externo,
[Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/):
[sourcecode:html]
<amp-analytics type="googleanalytics" config="https://example.com/analytics.account.config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
},
"vars": {
"account": "ABC123"
},
"extraUrlParams": {
"cd1": "AMP"
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
},
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
}
</script>
</amp-analytics>
[/sourcecode]
**Nota:** El código de ejemplo anterior está pensado para facilitar el aprendizaje, pero no se apoya en la realidad. Si trabajas con proveedores de herramientas de análisis, es probable que el ejemplo no tenga sentido. Las configuraciones de proveedores eliminan la complejidad. Consulta la documentación de tu proveedor de herramientas de análisis para obtener configuraciones de ejemplo.
## A dónde deben enviarse los datos de análisis: atributo “type”
AMP está diseñado para admitir dos patrones comunes de recopilación de datos:
* ingesta de un terminal del editor para sistemas de análisis internos;
* ingesta de un terminal del proveedor para la interoperabilidad con una solución del proveedor
(por ejemplo, [Adobe Analytics](https://helpx.adobe.com/marketing-cloud/analytics.html), [Chartbeat](http://support.chartbeat.com/docs/), [Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/)).
Para enviar datos del análisis a un proveedor de herramientas de análisis,
incluye el atributo `type` en la etiqueta `amp-analytics` y define su valor
para el proveedor correspondiente, como se define en la
[especificación de amp-analytics](/docs/reference/extended/amp-analytics.html).
Por ejemplo: `<amp-analytics type="googleanalytics">` envía datos de análisis
al proveedor de herramientas de análisis externo, Google Analytics.
Para enviar datos a un terminal del editor,
simplemente no incluyas el atributo `type`;
los datos del análisis se envían a los terminales definidos para cada
[solicitud](/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute).
Las configuraciones del proveedor de herramientas de análisis permiten dar rápidamente
los primeros pasos con `amp-analytics`.
Consulta la documentación y los recursos de ayuda
de tu proveedor para obtener información adicional.
Como se mencionó antes,
puedes encontrar la lista de proveedores que ya realizaron la integración con AMP y también los vínculos
a su documentación específica en la
[especificación de amp-analytics](/docs/reference/extended/amp-analytics.html).
Si eres proveedor de herramientas de análisis,
puedes obtener más información acerca de la
[integración de tu propia configuración de análisis en AMP HTML](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/integrating-analytics.md).
## Carga de la configuración remota: atributo config
No necesitas incluir la configuración completa de
`amp-analytics` en tu página de AMP.
Como alternativa, puedes llamar a una URL remota
para obtener todas las configuraciones o parte de ellas.
Esto te permite realizar acciones como modificar la configuración
en función de una solicitud específica.
Si como editor tienes control sobre el archivo remoto,
puedes realizar cualquier procesamiento en el servidor que sea necesario
para estructurar los datos de configuración.
El primer paso para cargar una configuración remota es
incluir el atributo config en la etiqueta `amp-analytics`:
[sourcecode:html]
<amp-analytics config="https://example.com/analytics.account.config.json">
[/sourcecode]
El siguiente paso es crear contenido JSON que se aloje en la URL remota.
En este ejemplo sencillo,
la configuración contenida en el objeto JSON corresponde solo al valor de la variable para la cuenta de análisis.
Ejemplo de contenido en `https://example.com/analytics.account.config.json`:
[sourcecode:html]
{
"vars": {
"account": "UA-XXXXX-Y" // Replace with your property ID.
}
}
[/sourcecode]
El paso final es asegurarte de que los datos del archivo remoto se extraigan
a la ubicación correcta en la configuración de `amp-analytics`.
En las solicitudes `pageview` y `event`,
el valor de la variable `account` se define automáticamente
en el valor de la cuenta de la URL remota (`"account": "UA-XXXXX-Y"`):
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
**Importante:** AMP no valida usos múltiples de la misma variable.
Los valores se completan siguiendo un orden de preferencia de sustitución de variables
y los valores en las direcciones URL remotas son los primeros en ese orden
(consulta [Orden de sustitución de variables](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
## Atributos requests, triggers y transport
El atributo `requests` define “los datos que se enviarán”
(por ejemplo, `pageviews`, `events`)
y el destino del envío (las direcciones URL empleadas para transmitir datos).
El atributo `triggers` describe el momento en que se deben enviar los datos del análisis;
por ejemplo, cuando un usuario visualiza una página o cuando un usuario hace clic en un vínculo.
El atributo `transport` especifica la manera de enviar una solicitud.
Dicho de una manera más específica, el protocolo.
Continúa leyendo para obtener más información acerca de estas configuraciones.
(También puedes hacerlo en la
[referencia de amp-analytics](/docs/reference/extended/amp-analytics.html)).
### Qué datos se envían: atributo requests
`request-name` se usa en la configuración del disparador para especificar
la solicitud que se debe enviar en respuesta a un evento específico.
`request-value` es una URL `https`.
Estos valores pueden incluir tokens de marcadores de posición
que pueden hacer referencia a otras solicitudes o variables.
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
Algunos proveedores de herramientas de análisis (incluido Google Analytics)
ya han proporcionado configuraciones
que tú usas a través del atributo `type`.
Si usas un proveedor de herramientas analíticas,
es posible que no necesites incluir información de `requests`.
Consulta la documentación de tu proveedor para averiguar
si se debe configurar `requests` y la manera de hacerlo.
#### Cómo anexar una URL de solicitud: Parámetros de URL adicionales
El atributo [extraUrlParams](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/amp-analytics.md#extra-url-params)
especifica parámetros adicionales para anexar a la cadena de consulta de la URL de consulta a través de la convención habitual "&foo=baz".
En el ejemplo de `amp-analytics` se agrega un parámetro adicional <code>cd1</code>
a la solicitud y se establece el valor del parámetro en "AMP":
[sourcecode:html]
"extraUrlParams": {
"cd1": "AMP"
}
[/sourcecode]
### Cuándo se envían los datos: atributo triggers
El atributo `triggers` describe cuándo se debe enviar una solicitud de análisis.
Contiene un par de valores claves: nombre y configuración del disparador.
El nombre del disparador puede ser cualquier cadena compuesta
por caracteres alfanuméricos (a-zA-Z0-9).
El siguiente
elemento `amp-analytics`, por ejemplo, se configura para enviar una solicitud a
`https://example.com/analytics` cuando el documento se carga por primera vez
y cada vez que se hace clic en una etiqueta `a`:
[sourcecode:html]
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
}
[/sourcecode]
AMP admite las siguientes configuraciones de disparadores:
<table>
<thead>
<tr>
<th data-th="Trigger Config" class="col-thirty">Config. del disparador</th>
<th data-th="Description">Descripción</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Trigger Config"><code>on</code> (obligatorio)</td>
<td data-th="Description">Evento que se debe recibir. Los valores válidos son <code>click</code>, <code>scroll</code>, <code>timer</code> y <code>visible</code>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>request</code> (obligatorio)</td>
<td data-th="Description">Nombre de la solicitud que se enviará (según se especifica en las solicitudes<a href="/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute"></a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>vars</code></td>
<td data-th="Description">Objeto que contiene pares de valores claves usados para sobrescribir <code>vars</code> definidos en la configuración de nivel superior o para especificar<code>vars</code> exclusivos de este disparador (consulta también<a href="/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering">Orden de sustitución de variables</a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>selector</code> (obligatorio cuando <code>on</code> se fija en <code>click</code>)</td>
<td data-th="Description">Selector de CSS usado para definir con precisión los elementos que deben someterse a seguimiento. Usa el valor <code>*</code> para realizar un seguimiento de todos los elementos. Esta configuración se usa junto con el disparador <code>click</code>. Obtén información acerca de cómo usar el selector para <a href="/docs/guides/analytics/use_cases.html#tracking-page-clicks">realizar un seguimiento de los clics de páginas</a> y las <a href="/docs/guides/analytics/use_cases.html#tracking-social-interactions">interacciones sociales</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>scrollSpec</code> (obligatorio cuando <code>on</code> se fija en <code>scroll</code>)</td>
<td data-th="Description">Controla las condiciones bajo las cuales se activa el evento <code>scroll</code> cuando se desplaza la página. Este objeto puede contener <code>verticalBoundaries</code> y <code>horizontalBoundaries</code>. Al menos una de las dos propiedades es obligatoria para que se active un evento <code>scroll</code>. Los valores para ambas propiedades deben ser arreglos de números que contengan los límites conforme a los cuales se genera un evento de desplazamiento. Consulta este ejemplo en <a href="/docs/guides/analytics/use_cases.html#tracking-scrolling">Seguimiento del desplazamiento</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>timerSpec</code> (obligatorio cuando <code>on</code> se fija en <code>timer</code>)</td>
<td data-th="Description">Controla el momento en que se activa el evento <code>timer</code>. El temporizador se activará de inmediato y, en adelante, a intervalos especificados. Esta configuración se usa junto con el elemento de activación <code>timer</code>.</td>
</tr>
</tbody>
</table>
**Importante:** Los disparadores de una configuración con menor precedencia se sobrescriben
con disparadores que tienen los mismos nombres de una configuración con mayor precedencia
(consulta [Orden de sustitución de variables](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
### Cómo se envían los datos: atributo transport
El atributo `transport` especifica la manera de enviar una solicitud.
De forma predeterminada, están habilitados los siguientes tres métodos:
<table>
<thead>
<tr>
<th data-th="Transport Method" class="col-thirty">Método de transport</th>
<th data-th="Description">Descripción</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Transport Method"><code>beacon</code></td>
<td data-th="Description">Indica que se puede usar <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a> para transmitir la solicitud. Enviará una solicitud <code>POST</code> con credenciales y un cuerpo vacío.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>xhrpost</code></td>
<td data-th="Description">Indica que se puede usar <code>XMLHttpRequest</code> para transmitir la solicitud. Enviará una solicitud <code>POST</code> con credenciales y un cuerpo vacío.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>image</code></td>
<td data-th="Description">Indica que la solicitud se puede enviar al generar una etiqueta <code>Image</code>. Esto enviará una solicitud <code>GET</code>.</td>
</tr>
</tbody>
</table>
Solo se usa un método de transporte;
es el de mayor precedencia
que esté habilitado, permitido y disponible.
La precedencia es `beacon` > `xhrpost` > `image`.
Si el agente de usuario del cliente no admite un método,
se usa el método de mayor precedencia que sigue.
Incluye el atributo `transport` en tu configuración
solo si deseas limitar las opciones de transporte;
de lo contrario, podrías detener las solicitudes.
En el ejemplo siguiente,
`beacon` y `xhrpost` se fijan en false
para no usarse aunque tengan mayor precedencia que `image`.
Si el agente de usuario del cliente admite el método `image`,
es el que se usará; de lo contrario, no se enviarán solicitudes.
[sourcecode:html]
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
[/sourcecode]
## Orden de sustitución de variables
AMP completa variables con valores en orden de precedencia:
1. Configuraciones remotas (a través de `config`).
2. `vars` anidados dentro de un disparador en `triggers`.
3. `vars` del nivel superior anidados en `amp-analytics`.
4. Valores proporcionados por la plataforma.
En este ejemplo hay una configuración remota,
variables definidas en el nivel superior, en disparadores y en el nivel de la plataforma:
[sourcecode:html]
<amp-analytics config="http://example.com/config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}&clientId=${clientId(cid-scope)}",
},
"vars": {
"account": "ABC123",
"title": "Homepage"
},
"triggers": {
"some-event": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "My homepage",
"clientId": "my user"
}
}
}
</script>
</amp-analytics>
[/sourcecode]
Cuando se define el mismo `var` en múltiples ubicaciones,
el orden de precedencia de la variable establece su valor una vez.
De esta manera, si la configuración remota definió `account` como UA-XXXXX-Y en el ejemplo anterior,
los valores de diferentes vars serán los siguientes:
<table>
<thead>
<tr>
<th data-th="var" class="col-thirty"><code>var</code></th>
<th data-th="Value">Valor</th>
<th data-th="Defined By" class="col-thirty">Definido por</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="var"><code>canonicalUrl</code></td>
<td data-th="Value"><code>http://example.com/path/to/the/page</code></td>
<td data-th="Defined By">Plataforma</td>
</tr>
<tr>
<td data-th="var"><code>title</code></td>
<td data-th="Value">My homepage</td>
<td data-th="Defined By">Disparador</td>
</tr>
<tr>
<td data-th="var"><code>account</code></td>
<td data-th="Value"><code>UA-XXXXX-Y</code></td>
<td data-th="Defined By">Configuración remota</td>
</tr>
<tr>
<td data-th="var"><code>clientId</code></td>
<td data-th="Value">my user</td>
<td data-th="Defined By">Disparador</td>
</tr>
</tbody>
</table>
```
--------------------------------------------------------------------------------
/content/docs/guides/deploy/analytics_amp/[email protected]:
--------------------------------------------------------------------------------
```markdown
---
$title: Eingehende Betrachtung der AMP-Analyse
---
In dieser Anleitung wird genauer auf die [amp-analytics-Komponente](/docs/reference/extended/amp-analytics.html) eingegangen. Dabei wird eine `amp-analytics`-Beispielkonfiguration in die folgenden Grundbausteine unterteilt:
[TOC]
Im übrigen Teil dieser Anleitung wird das folgende Konfigurationsbeispiel verwendet, mit dem Seitenaufrufe und Nutzerklicks auf Links erfasst und die Analysedaten an den Drittanbieter [Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/) gesendet werden:
[sourcecode:html]
<amp-analytics type="googleanalytics" config="https://example.com/analytics.account.config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
},
"vars": {
"account": "ABC123"
},
"extraUrlParams": {
"cd1": "AMP"
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
},
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
}
</script>
</amp-analytics>
[/sourcecode]
**Hinweis:** Der obige Beispielcode ist als Lernhilfe gedacht und stellt kein realistisches Anwendungsbeispiel dar. Wenn Sie mit Analyseanbietern zusammenarbeiten, ist das obige Beispiel wahrscheinlich nicht sinnvoll. Anbieterkonfigurationen verringern die Komplexität. Weitere Beispielkonfigurationen können Sie wahrscheinlich der Dokumentation des Analyseanbieters entnehmen.
## Ziel für das Senden der Analysedaten: type-Attribut
AMP wurde entwickelt, zwei gebräuchliche Muster der Datenerfassung zu unterstützen:
* Aufnahme durch einen Publisher-Endpunkt für interne Analysesysteme
* Aufnahme durch einen Anbieterendpunkt für die Interoperabilität mit einer Anbieterlösung wie z. B. [Adobe Analytics](https://helpx.adobe.com/marketing-cloud/analytics.html), [Chartbeat](http://support.chartbeat.com/docs/) oder [Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/)
Wenn Sie Analysedaten an einen Analyseanbieter senden möchten, schließen Sie das `type`-Attribut in das `amp-analytics`-Tag ein und legen Sie als Wert den gewünschten Anbieter fest, wie in der [amp-analytics-Spezifikation](/docs/reference/extended/amp-analytics.html) beschrieben.
Mit `<amp-analytics type="googleanalytics">` werden beispielsweise Analysedaten an den Analysedrittanbieter Google Analytics gesendet.
Wenn Sie Daten an einen Publisher-Endpunkt senden möchten, schließen Sie einfach nicht das `type`-Attribut ein. Die Analysedaten werden dann an die für die jeweilige [Anforderung](/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute) festgelegten Endpunkte gesendet.
Konfigurationen von Analyseanbietern ermöglichen einen schnellen Einstieg in die Verwendung von `amp-analytics`.
Weitere Informationen finden Sie in der Dokumentation und den Hilferessourcen Ihres Anbieters.
Eine Liste der Anbieter, die in AMP integriert werden können, sowie Links zur entsprechenden Dokumentation finden Sie wie bereits erwähnt in der [amp-analytics-Spezifikation](/docs/reference/extended/amp-analytics.html).
Wenn Sie selbst Analyseanbieter sind, können Sie [hier mehr über die Integration Ihrer eigenen Analysekonfiguration in AMP-HTML erfahren](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/integrating-analytics.md).
## Remote-Konfiguration laden: config-Attribut
Sie brauchen nicht die gesamte Konfiguration für `amp-analytics` auf Ihrer AMP-Seite einzuschließen.
Stattdessen können Sie die Konfigurationen vollständig oder teilweise von einer Remote-URL abrufen.
Dies ermöglicht Ihnen beispielsweise, die Konfiguration in Abhängigkeit von der jeweiligen Anforderung zu variieren. Wenn Sie als Publisher die Kontrolle über die Remote-Datei haben, können Sie die serverseitige Verarbeitung vornehmen, die für die Erstellung der Konfigurationsdaten erforderlich ist.
Der erste Schritt zum Laden von Remote-Konfigurationen besteht darin, das config-Attribut in das `amp-analytics`-Tag einzuschließen:
[sourcecode:html]
<amp-analytics config="https://example.com/analytics.account.config.json">
[/sourcecode]
Im nächsten Schritt erstellen Sie den JSON-Inhalt unter der Remote-URL. In diesem einfachen Beispiel umfasst die im JSON-Objekt enthaltene Konfiguration lediglich den Variablenwert für das Analysekonto.
Beispielinhalt in `https://example.com/analytics.account.config.json`:
[sourcecode:js]
{
"vars": {
"account": "UA-XXXXX-Y" // Replace with your property ID.
}
}
[/sourcecode]
Im letzten Schritt sorgen Sie dafür, dass der Inhalt der Remote-Datei an der richtigen Stelle in der `amp-analytics`-Konfiguration platziert wird.
Sowohl in der `pageview`- als auch in der `event`-Anforderung wird hier der `account`-Variablenwert automatisch auf den Kontowert in der Remote-URL (`"account": "UA-XXXXX-Y"`) gesetzt:
[sourcecode:js]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
**Wichtig:** AMP prüft nicht, ob dieselbe Variable mehrfach verwendet wird.
Werte werden in einer bestimmten Reihenfolge der Variablensubstitution festgelegt und Werte in Remote-URLs stehen am Anfang dieser Reihenfolge (siehe [Reihenfolge der Variablensubstitution](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
## Anforderungen, Trigger und Transporte
Mit dem `requests`-Attribut wird festgelegt, welche Daten (z. B. `pageviews` und `events`) wohin (an welche URLs) gesendet werden.
Mit dem `triggers`-Attribut wird beschrieben, wann Analysedaten gesendet werden sollen, z. B. wenn ein Nutzer eine Seite aufruft oder wenn er auf einen Link klickt.
Mit dem `transport`-Attribut wird angegeben, wie eine Anforderung gesendet wird, also das konkrete Protokoll.
Im Folgenden wird näher auf diese Konfigurationen eingegangen.
Außerdem finden Sie weitere Informationen in der [amp-analytics-Referenz](/docs/reference/extended/amp-analytics.html).
### Art der gesendeten Daten: requests-Attribut
Mit `request-name` wird in der Triggerkonfiguration angegeben, welche Anforderung als Antwort auf ein bestimmtes Ereignis gesendet werden soll.
`request-value` ist eine `https`-URL. Diese Werte können Platzhaltertoken enthalten, die auf weitere Anforderungen oder Variablen verweisen.
[sourcecode:js]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
Einige Analyseanbieter, einschließlich Google Analytics, haben bereits eine Konfiguration bereitgestellt, die Sie mithilfe des `type`-Attributs verwenden können.
Wenn Sie einen Analyseanbieter verwenden, brauchen Sie möglicherweise keine `requests`-Informationen anzugeben.
Ob und wie `requests` konfiguriert werden muss, entnehmen Sie der Anbieterdokumentation.
#### Anforderungs-URL anhängen: zusätzliche URL-Parameter
Mit dem Attribut [extraUrlParams](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/amp-analytics.md#extra-url-params) werden zusätzliche Parameter angegeben, die über die gewohnte "&foo=baz"-Konvention an den Abfragestring der Anforderungs-URL angehängt werden.
Im `amp-analytics`-Beispiel wird der Anforderung ein zusätzlicher Parameter `cdl` hinzugefügt und der Parameterwert auf "AMP" gesetzt:
[sourcecode:js]
"extraUrlParams": {
"cd1": "AMP"
}
[/sourcecode]
### Bedingungen für das Senden von Daten: triggers-Attribut
Über das `triggers`-Attribut wird angegeben, wann eine Analyseanforderung gesendet werden soll.
Es enthält ein Schlüssel/Wert-Paar aus Triggername und Triggerkonfiguration.
Der Triggername kann ein beliebiger String aus alphanumerischen Zeichen (a–z, A–Z, 0–9) sein.
Das folgende `amp-analytics`-Element sorgt z. B. dafür, dass beim ersten Laden des Dokuments und bei jedem Klick auf ein `https://example.com/analytics`-Tag eine Anforderung an `a` gesendet wird:
[sourcecode:js]
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
}
[/sourcecode]
AMP unterstützt die folgenden Triggerkonfigurationen:
<table>
<thead>
<tr>
<th class="col-thirty" data-th="Trigger Config">Trigger-konfiguration</th>
<th data-th="Description">Beschreibung</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Trigger Config"><code>on</code> (erforderlich)</td>
<td data-th="Description">Das Ereignis, auf das gewartet wird. Gültige Werte sind <code>click</code>, <code>scroll</code>, <code>timer</code> und <code>visible</code>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>request</code> (erforderlich)</td>
<td data-th="Description">Name der zu sendenden Anforderung, wie unter [Anforderungen](/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute) angegeben</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>vars</code></td>
<td data-th="Description">Ein Objekt, das Schlüssel/Wert-Paare enthält, mit denen in der Konfiguration oberster Ebene festgelegte <code>vars</code>-Variablen überschrieben oder spezifische <code>vars</code>-Variablen für diesen Trigger angegeben werden (siehe auch [Reihenfolge der Variablensubstitution](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering))</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>selector</code> (erforderlich, wenn <coe>on</code> auf <code>click</code> gesetzt ist)</td>
<td data-th="Description">Ein CSS-Selektor dient zur genaueren Angabe der zu erfassenden Elemente. Bei Verwendung von <code>*</code> werden alle Elemente erfasst. Diese Konfiguration wird in Verbindung mit dem <code>click</code>-Trigger eingesetzt. [Informationen zur Verwendung des Selektors zum Erfassen von Seitenklicks](/docs/guides/analytics/use_cases.html#tracking-page-clicks) und von [Interaktionen über soziale Netzwerke](/docs/guides/analytics/use_cases.html#tracking-social-interactions)</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>scrollSpec</code> (erforderlich, wenn <code>on</code> auf <code>scroll</code> gesetzt ist)</td>
<td data-th="Description">Hiermit wird festgelegt, unter welchen Bedingungen beim Scrollen auf der Seite das <code>scroll</code>-Ereignis ausgelöst wird. Dieses Objekt kann <code>verticalBoundaries</code> und <code>horizontalBoundaries</code> enthalten. Für das Auslösen eines <code>scroll</code>-Ereignisses ist mindestens eine der zwei Eigenschaften erforderlich. Bei den Werten für beide Eigenschaften sollte es sich um Arrays von Zahlen handeln, die die Grenzen angeben, bei denen ein scroll-Ereignis generiert wird. [Beispiel zum Erfassen des Scrollens](/docs/guides/analytics/use_cases.html#tracking-scrolling)</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>timerSpec</code> (erforderlich, wenn <code>on</code> auf <code>timer</code> gesetzt ist)</td>
<td data-th="Description">Hiermit wird festgelegt, wann das <code>timer</code>-Ereignis ausgelöst wird. Der Timer wird sofort und anschließend nach Ablauf eines angegebenen Intervalls ausgelöst. Diese Konfiguration wird in Verbindung mit dem <code>timer</code>-Trigger verwendet.</td>
</tr>
</tbody>
</table>
**Wichtig:** Trigger aus einer Konfiguration mit einer niedrigeren Priorität werden von gleichnamigen Triggern aus einer Konfiguration höherer Priorität überschrieben (siehe [Reihenfolge der Variablensubstitution](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
### Methode für das Senden von Daten: transport-Attribut
Mit dem `transport`-Attribut wird angegeben, wie eine Anforderung gesendet wird. Standardmäßig sind die drei folgenden Methoden aktiviert:
<table>
<thead>
<tr>
<th class="col-thirty" data-th="Transport Method">Transport-methode</th>
<th data-th="Description">Beschreibung</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Transport Method"><code>beacon</code></td>
<td data-th="Description">Hiermit wird angegeben, dass die Anforderung mittels [navigator.sendBeacon](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon) übertragen werden kann. Dadurch wird eine <code>POST</code>-Anforderung mit Anmeldedaten und einem leeren body-Abschnitt gesendet.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>xhrpost</code></td>
<td data-th="Description">Hiermit wird angegeben, dass die Anforderung mittels <code>XMLHttpRequest</code> übertragen werden kann. Dadurch wird eine <code>POST</code>-Anforderung mit Anmeldedaten und einem leeren body-Abschnitt gesendet.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>image</code></td>
<td data-th="Description">Hiermit wird angegeben, dass die Anforderung durch Generieren eines <code>Image</code>-Tags gesendet werden kann. Dadurch wird eine <code>GET</code>-Anforderung gesendet.</td>
</tr>
</tbody>
</table>
Es wird nur eine einzige Transportmethode verwendet, und zwar jene mit der höchsten Priorität, die aktiviert, zulässig und verfügbar wird.
Die Prioritätsreihenfolge lautet `beacon` > `xhrpost` > `image`.
Wenn der User-Agent des Kunden eine Methode nicht unterstützt, wird die aktivierte Methode mit der höchsten verfügbaren Priorität verwendet.
Schließen Sie das `transport`-Attribut nur dann in Ihre Konfiguration ein, wenn Sie die Transportoptionen beschränken möchten. Andernfalls könnten Anforderungen unterbunden werden.
Im unten stehenden Beispiel sind `beacon` und `xhrpost` auf "false" gesetzt und werden daher nicht verwendet, obwohl sie eine höhere Priorität als `image` haben.
Wenn der User-Agent des Kunden die `image`-Methode unterstützt, wird sie auch verwendet. Andernfalls wird keine Anforderung gesendet.
[sourcecode:js]
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
[/sourcecode]
## Reihenfolge der Variablensubstitution
AMP legt Werte für die Variablen entsprechend der Prioritätsreihenfolge fest:
1. Remote-Konfigurationen (über `config`)
2. `vars`-Variablen, die in einen Trigger innerhalb von `triggers` eingebettet sind
3. `vars`-Variablen oberster Ebene, die in `amp-analytics` eingebettet sind
4. Von der Plattform bereitgestellte Werte
In diesem Beispiel gibt es eine Remote-Konfiguration sowie Variablen, die auf oberster Ebene, in Triggern und auf Plattformebene festgelegt sind:
[sourcecode:html]
<amp-analytics config="http://example.com/config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}&clientId=${clientId(cid-scope)}",
},
"vars": {
"account": "ABC123",
"title": "Homepage"
},
"triggers": {
"some-event": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "My homepage",
"clientId": "my user"
}
}
}
</script>
</amp-analytics>
[/sourcecode]
Wenn dieselbe `var`-Variable an mehreren Stellen festgelegt wird, entscheidet die Prioritätsreihenfolge der Variablen über ihren Wert.
Wenn also im obigen Beispiel in der Remote-Konfiguration für `account` der Wert UA-XXXXX-Y festgelegt wird, haben die Variablen die folgenden Werte:
<table>
<thead>
<tr>
<th class="col-thirty" data-th="var"><code>var</code></th>
<th data-th="Value">Wert</th>
<th class="col-thirty" data-th="Defined By">Definiert durch</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="var"><code>canonicalUrl</code></td>
<td data-th="Value"><code>http://example.com/path/to/the/page</code></td>
<td data-th="Defined By">Plattform</td>
</tr>
<tr>
<td data-th="var"><code>title</code></td>
<td data-th="Value">My homepage</td>
<td data-th="Defined By">Trigger</td>
</tr>
<tr>
<td data-th="var"><code>account</code></td>
<td data-th="Value"><code>UA-XXXXX-Y</code></td>
<td data-th="Defined By">Remote-Konfiguration</td>
</tr>
<tr>
<td data-th="var"><code>clientId</code></td>
<td data-th="Value">my user</td>
<td data-th="Defined By">Trigger</td>
</tr>
</tbody>
</table>
```
--------------------------------------------------------------------------------
/content/docs/guides/deploy/analytics_amp/[email protected]:
--------------------------------------------------------------------------------
```markdown
---
$title: Immersione nel mondo di AMP Analytics
toc: true
---
[TOC]
Questa guida si addentra nella sfera del
[componente amp-analytics](/docs/reference/extended/amp-analytics.html),
scomponendo una configurazione campione di `amp-analytics` in questi blocchi predefiniti:
Il resto di questa guida usa il campione di configurazione,
che consente di monitorare le visualizzazioni di pagina e i clic dell’utente sui link
e inviare i dati di analisi al fornitore di terze parti,
[Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/):
[sourcecode:html]
<amp-analytics type="googleanalytics" config="https://example.com/analytics.account.config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
},
"vars": {
"account": "ABC123"
},
"extraUrlParams": {
"cd1": "AMP"
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
},
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
}
</script>
</amp-analytics>
[/sourcecode]
**Nota:** il codice dell’esempio sopra è stato creato per aiutarti a capire ma non costituisce assolutamente un campione realistico. Se collabori con fornitori di strumenti di analisi, è probabile che il campione sopra non abbia senso, in quanto le configurazioni dei fornitori eliminano le complessità. Per le configurazioni di esempio fai riferimento alla documentazione del tuo fornitore di strumenti di analisi.
## Dove inviare i dati di analisi: attributo type
AMP è progettato per supportare due modelli diffusi di raccolta dati:
* Inserimento da un endpoint di proprietà di un publisher per i sistemi di analisi interni.
* Inserimento da un endpoint di proprietà di un fornitore per l’interoperabilità con la soluzione del fornitore
(ad esempio, [Adobe Analytics](https://helpx.adobe.com/marketing-cloud/analytics.html), [Chartbeat](http://support.chartbeat.com/docs/), [Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/)).
Per inviare i dati dell’analisi a un fornitore di strumenti di analisi,
includi l’attributo `type` nel tag `amp-analytics` e imposta il suo valore
per il fornitore pertinente, come definito nella
[specifica amp-analytics](/docs/reference/extended/amp-analytics.html).
Ad esempio: `<amp-analytics type="googleanalytics">` invia i dati di analisi
al fornitore di strumenti di analisi di terze parti, Google Analytics.
Per inviare i dati a un endpoint di proprietà di un publisher
è sufficiente non includere l’attributo `type`,
i dati di analisi vengono quindi inviati agli endpoint definiti per ciascuna
[richiesta](/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute).
Le configurazioni del fornitore di strumenti di analisi costituiscono un sistema rapido
per iniziare a lavorare con `amp-analytics`.
Per ulteriori informazioni è opportuno consultare la documentazione
e le risorse di riferimento rese disponibili dal fornitore.
Come precedentemente indicato,
l’elenco di fornitori che hanno già incluso l’integrazione con AMP, nonché i link
alla rispettiva documentazione specifica sono reperibili nella
[specifica amp-analytics](/docs/reference/extended/amp-analytics.html).
Se sei un fornitore di strumenti di analisi,
ottieni ulteriori informazioni sull’
[integrazione della tua configurazione di analisi personale in HTML AMP](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/integrating-analytics.md).
## Caricamento della configurazione remota: attributo config
Non hai bisogno di includere tutta la
configurazione per `amp-analytics` nella tua pagina AMP.
Al contrario, puoi richiamare un URL remoto
per la totalità o per parte delle configurazioni.
Questo ti consente di eseguire operazioni come la modifica
della configurazione in base a una richiesta specifica.
Se in quanto editore hai il controllo sul file remoto,
puoi eseguire qualsiasi operazione di elaborazione necessaria sul lato server
per costruire i dati di configurazione.
Il primo passo per caricare le configurazioni remote
è quello di includere l’attributo config nel tag `amp-analytics`:
[sourcecode:html]
<amp-analytics config="https://example.com/analytics.account.config.json">
[/sourcecode]
Il passo successivo è quello di creare il contenuto JSON che risiede nell’URL remoto.
In questo semplice esempio,
la configurazione contenuta nell’oggetto JSON è semplicemente il valore della variabile per l’account di analisi.
Contenuto di esempio in `https://example.com/analytics.account.config.json`:
[sourcecode:html]
{
"vars": {
"account": "UA-XXXXX-Y" // Replace with your property ID.
}
}
[/sourcecode]
Il passo finale è quello di verificare che il contenuto del file remoto sia
inserito nel punto corretto nella configurazione `amp-analytics`.
Qui, in entrambe le richieste `pageview` e `event`,
il valore della variabile `account` è automaticamente impostato
sul valore dell’account nell’URL remoto (`"account": "UA-XXXXX-Y"`):
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
**Importante.** AMP non consente la convalida rispetto a più usi della stessa variabile.
I valori vengono inseriti seguendo un ordine di preferenza di sostituzione delle variabili
e i valori negli URL remoti sono all’inizio di tale ordine
(vedi [Ordinamento della sostituzione delle variabili](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
## Richieste, attivazioni e trasferimenti
L’attributo `requests` definisce ‘quali dati vengono inviati’
(ad esempio, `pageviews`, `events`)
e dove vengono inviati (gli URL utilizzati per trasmettere i dati).
L’attributo `triggers` indica quando devono essere inviati i dati di analisi,
ad esempio, quando un utente visualizza una pagina o quando un utente fa clic su un link.
L’attributo `transport` specifica come inviare una richiesta,
più in particolare, il protocollo.
Più avanti puoi ottenere ulteriori informazioni su queste configurazioni
(puoi anche approfondire queste configurazioni nel
[riferimento amp-analytics](/docs/reference/extended/amp-analytics.html)).
### Quali dati vengono inviati: attributo requests
Il valore `request-name` viene utilizzato nella configurazione di attivazione per specificare
quale richiesta deve essere inviata in risposta a un particolare evento.
Il valore `request-value` è un URL `https`.
Questi valori possono includere token segnaposto
che fanno riferimento ad altre richieste o variabili.
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
Alcuni fornitori di strumenti di analisi (compreso Google Analytics)
hanno già fornito la configurazione
da utilizzare tramite l’attributo `type`.
Se stai usando un fornitore di strumenti di analisi,
è possibile che non sia necessario includere le informazioni `requests`.
Fai riferimento alla documentazione del tuo fornitore per
sapere se occorre configurare l’attributo `requests` ed eventualmente come configurarlo.
#### Aggiunta di URL di richiesta: Extra URL Params
L’attributo [extraUrlParams](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/amp-analytics.md#extra-url-params)
specifica i parametri supplementari da aggiungere alla stringa di query dell’URL di richiesta tramite la solita convenzione "&foo=baz".
L’esempio `amp-analytics` aggiunge un ulteriore parametro <code>cd1</code>
alla richiesta e imposta il valore del parametro su "AMP":
[sourcecode:html]
"extraUrlParams": {
"cd1": "AMP"
}
[/sourcecode]
### Quando vengono inviati i dati: attributo triggers
L’attributo `triggers` descrive quando deve essere inviata una richiesta di analisi.
Contiene una coppia chiave-valore di nome-trigger e configurazione-trigger.
Il nome trigger può essere qualsiasi stringa costituita da
caratteri alfanumerici (a-zA-Z0-9).
Ad esempio,
il seguente elemento `amp-analytics` è configurato per inviare una richiesta a
`https://example.com/analytics` quando il documento viene caricato per la prima volta
e ogni volta che viene fatto clic su un tag `a`:
[sourcecode:html]
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
}
[/sourcecode]
AMP supporta le seguenti configurazioni di attivazione:
<table>
<thead>
<tr>
<th data-th="Trigger Config" class="col-thirty">Trigger Config</th>
<th data-th="Description">Descrizione</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Trigger Config"><code>on</code> (obbligatorio)</td>
<td data-th="Description">L’evento per cui invocare il listener. I valori validi sono <code>click</code>, <code>scroll</code>, <code>timer</code> e <code>visible</code>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>request</code> (obbligatorio)</td>
<td data-th="Description">Nome della richiesta da inviare (come specificato nelle <a href="/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute">richieste</a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>vars</code></td>
<td data-th="Description">Un oggetto contenente le coppie chiave-valore usate per eseguire l’override delle <code>vars</code> definite nella configurazione di primo livello o per specificare <code>vars</code> univoche a questo trigger (vedi anche <a href="/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering">Ordinamento della sostituzione delle variabili</a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>selector</code> (obbligatorio quando <code>on</code> è impostato su <code>click</code>)</td>
<td data-th="Description">Un selettore CSS utilizzato per definire meglio quali elementi devono essere monitorati. Usa il valore <code>*</code> per monitorare tutti gli elementi. Questa configurazione viene utilizzata insieme al trigger <code>click</code>. Scopri come usare il selettore per <a href="/docs/guides/analytics/use_cases.html#tracking-page-clicks">monitorare i clic di pagina</a> e per le <a href="/docs/guides/analytics/use_cases.html#tracking-social-interactions">interazioni sui social</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>scrollSpec</code> (obbligatorio quando <code>on</code> è impostato su <code>scroll</code>)</td>
<td data-th="Description">Controlla in base a quali condizioni viene attivato l’evento <code>scroll</code> quando l’utente scorre la pagina. Questo oggetto può contenere <code>verticalBoundaries</code> e <code>horizontalBoundaries</code>. Per l’attivazione di un evento <code>scroll</code> è necessaria almeno una delle due proprietà. I valori per entrambe le proprietà devono essere serie di numeri contenenti i limiti entro i quali viene generato un evento di scorrimento. Vedi questo esempio sul <a href="/docs/guides/analytics/use_cases.html#tracking-scrolling">monitoraggio dello scorrimento</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>timerSpec</code> (obbligatorio quando <code>on</code> è impostato su <code>timer</code>)</td>
<td data-th="Description">Controlla quando viene attivato l’evento <code>timer</code>. Il timer si attiva immediatamente e successivamente a intervalli specifici. Questa configurazione viene utilizzata insieme al trigger <code>timer</code>.</td>
</tr>
</tbody>
</table>
**Importante:** i trigger di una configurazione con precedenza più bassa vengono ignorati
dai trigger con lo stesso nome di una configurazione con una precedenza più alta
(vedi [Ordinamento della sostituzione delle variabili](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
### Come vengono inviati i dati: attributo transport
L’attributo `transport` specifica come inviare una richiesta.
I seguenti tre metodi sono abilitati per impostazione predefinita:
<table>
<thead>
<tr>
<th data-th="Transport Method" class="col-thirty">Metodo di trasferimento</th>
<th data-th="Description">Descrizione</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Transport Method"><code>beacon</code></td>
<td data-th="Description">Indica che <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a> può essere utilizzato per trasmettere la richiesta. Viene inviata una richiesta <code>POST</code>, completa di credenziali, con il corpo del testo vuoto.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>xhrpost</code></td>
<td data-th="Description">Indica che <code>XMLHttpRequest</code> può essere utilizzato per trasmettere la richiesta. Viene inviata una richiesta <code>POST</code>, completa di credenziali, con il corpo del testo vuoto.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>image</code></td>
<td data-th="Description">Indica che la richiesta può essere inviata generando un tag <code>Image</code>. Questo invia una richiesta <code>GET</code>.</td>
</tr>
</tbody>
</table>
Viene utilizzato solo un metodo di trasferimento
ed è quello abilitato, consentito e disponibile
con la precedenza più alta.
La precedenza è `beacon` > `xhrpost` > `image`.
Se l’agente utente del client non supporta un metodo,
viene utilizzato il metodo successivo abilitato con la precedenza più alta.
Include l’attributo `transport` nella configurazione
solo se si desidera limitare le opzioni di trasferimento,
in caso contrario si possono interrompere le richieste.
Nell’esempio di seguito,
`beacon` e `xhrpost` sono impostati su false,
in modo tale da non essere utilizzati anche se hanno una precedenza più alta rispetto a `image`.
Se l’agente utente del client supporta il metodo `image`,
verrà utilizzato, in contrario non sarà inviata alcuna richiesta.
[sourcecode:html]
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
[/sourcecode]
## Ordinamento della sostituzione delle variabili
AMP inserisce le variabili con i valori in ordine di precedenza:
1. Configurazioni remote (tramite `config`).
2. `vars` nidificate all’interno di un trigger in `triggers`.
3. `vars` al primo livello nidificate in `amp-analytics`.
4. Valori forniti dalla piattaforma.
In questo esempio sono presenti una configurazione remota,
variabili definite al primo livello, nei trigger e a livello della piattaforma:
[sourcecode:html]
<amp-analytics config="http://example.com/config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}&clientId=${clientId(cid-scope)}",
},
"vars": {
"account": "ABC123",
"title": "Homepage"
},
"triggers": {
"some-event": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "My homepage",
"clientId": "my user"
}
}
}
</script>
</amp-analytics>
[/sourcecode]
Quando la stessa `var` è definita in più posizioni,
l’ordine delle variabili di precedenza ne imposta il valore una volta.
Pertanto, se la configurazione remota definiva `account` come UA-XXXXX-Y nell’esempio sopra,
i valori delle diverse vars saranno come indicato di seguito:
<table>
<thead>
<tr>
<th data-th="var" class="col-thirty"><code>var</code></th>
<th data-th="Value">Valore</th>
<th data-th="Defined By" class="col-thirty">Definito da</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="var"><code>canonicalUrl</code></td>
<td data-th="Value"><code>http://example.com/path/to/the/page</code></td>
<td data-th="Defined By">Piattaforma</td>
</tr>
<tr>
<td data-th="var"><code>title</code></td>
<td data-th="Value">My homepage</td>
<td data-th="Defined By">Trigger</td>
</tr>
<tr>
<td data-th="var"><code>account</code></td>
<td data-th="Value"><code>UA-XXXXX-Y</code></td>
<td data-th="Defined By">Configurazione remota</td>
</tr>
<tr>
<td data-th="var"><code>clientId</code></td>
<td data-th="Value">my user</td>
<td data-th="Defined By">Trigger</td>
</tr>
</tbody>
</table>
```
--------------------------------------------------------------------------------
/content/docs/guides/deploy/analytics_amp/[email protected]:
--------------------------------------------------------------------------------
```markdown
---
$title: AMP Analytics dans le détail
toc: true
---
[TOC]
Ce guide propose une analyse détaillée du
[composant amp-analytics](/docs/reference/extended/amp-analytics.html),
en divisant un exemple de configuration de la balise `amp-analytics` en quatre catégories principales :
Le reste de ce guide utilise cet exemple de configuration
qui effectue le suivi des vues de page et des clics des utilisateurs sur des liens,
et envoie les données d'analyse à un fournisseur tiers,
[Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/):
[sourcecode:html]
<amp-analytics type="googleanalytics" config="https://example.com/analytics.account.config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
},
"vars": {
"account": "ABC123"
},
"extraUrlParams": {
"cd1": "AMP"
},
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
},
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
}
</script>
</amp-analytics>
[/sourcecode]
**Remarque :** Le code illustré ci-dessus est fourni à titre d'exemple pour vous aider à apprendre, mais il ne constitue en rien un exemple réaliste. Si vous travaillez avec des fournisseurs de solutions d'analyse, il est probable que cet exemple n'ait pas de sens ; les configurations du fournisseur simplifieront les choses. Pour obtenir des exemples de configuration de votre fournisseur, consultez sa documentation.
## Où envoyer les données d'analyse : l'attribut type
AMP est conçu pour prendre en charge deux modèles courants de collecte des données :
* L'ingestion par un point d'extrémité appartenant à un éditeur pour les systèmes d'analyse interne
* L'ingestion par un point d'extrémité appartenant à un fournisseur aux fins d'interopérabilité avec la solution du fournisseur
(par exemple, [Adobe Analytics](https://helpx.adobe.com/marketing-cloud/analytics.html), [Chartbeat](http://support.chartbeat.com/docs/) ou encore [Google Analytics](https://developers.google.com/analytics/devguides/collection/amp-analytics/))
Pour envoyer des données d'analyse à un fournisseur de solutions d'analyse,
incluez l'attribut `type` dans la balise `amp-analytics`,
et définissez sa valeur sur le fournisseur approprié, tel que défini dans la
[spécification du composant amp-analytics](/docs/reference/extended/amp-analytics.html).
Par exemple, `<amp-analytics type="googleanalytics">` envoie les données d'analyse
au fournisseur de solutions d'analyse tiers Google Analytics.
Pour envoyer les données à un point d'extrémité appartenant à l'éditeur,
il vous suffit de ne pas inclure l'attribut `type` ;
les données d'analyse sont envoyées aux points d'extrémité définis pour chaque
[requête](/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute).
Les configurations des fournisseurs de solutions d'analyse constituent
un bon point de départ pour commencer avec le composant `amp-analytics`.
Pour en savoir plus, consultez la documentation et
les ressources d'aide de votre fournisseur.
Comme nous l'avons déjà indiqué,
la liste des fournisseurs qui proposent déjà une intégration AMP ainsi que des liens
vers leurs ressources respectives sont disponibles dans la
[spécification du composant amp-analytics](/docs/reference/extended/amp-analytics.html).
Si vous êtes un fournisseur de solutions d'analyse,
découvrez comment
[intégrer votre propre configuration d'analyse dans AMP HTML](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/integrating-analytics.md).
## Charger une configuration distante : l'attribut config
Il n'est pas nécessaire d'inclure toutes les configurations
de `amp-analytics` dans votre page AMP.
En lieu et place, vous pouvez appeler une URL distante
pour tout ou partie des configurations.
Cela vous permet entre autres de faire varier la configuration
en fonction d'une requête spécifique.
Si, en tant qu'éditeur, vous avez le contrôle du fichier distant,
vous pouvez effectuer tout traitement nécessaire côté serveur
pour créer les données de configuration.
Pour charger les configurations distantes, la première étape consiste à
inclure l'attribut config dans la balise `amp-analytics` :
[sourcecode:html]
<amp-analytics config="https://example.com/analytics.account.config.json">
[/sourcecode]
L'étape suivante consiste à créer le contenu JSON qui réside dans l'URL distante.
Dans cet exemple simple,
la configuration contenue dans l'objet JSON est juste la valeur de variable due compte d'analyse.
Exemple de contenu dans `https://example.com/analytics.account.config.json` :
[sourcecode:html]
{
"vars": {
"account": "UA-XXXXX-Y" // Replace with your property ID.
}
}
[/sourcecode]
La dernière étape consiste à vous assurer que ce qui se trouve dans le fichier distant
est inséré à l'endroit approprié dans la configuration de `amp-analytics`.
Dans les requêtes `pageview` et `event` de cet exemple,
la valeur de la variable `account` est automatiquement
définie sur la valeur du compte indiqué dans l'URL distante (`"account": "UA-XXXXX-Y"`) :
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
**Important :** AMP ne valide pas les usages multiples d'une même variable.
Les valeurs sont renseignées en fonction d'un ordre de préférence de substitution des variables,
et les valeurs indiquées dans les URL distantes sont en première position
(voir [Ordonnancement de la substitution des variables](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
## Les attributs requests, triggers et transport
L'attribut `requests` détermine quelles données sont envoyées
(par exemple `pageviews` ou `events`)
et où ces données sont envoyées (les URL utilisées pour transmettre les données).
L'attribut `triggers` indique à quel moment les données d'analyse doivent être envoyées,
par exemple lorsqu'un utilisateur affiche une page ou clique sur un lien.
L'attribut `transport` indique comment envoyer une requête,
et plus spécifiquement le protocole.
Lisez la suite pour en savoir plus sur ces configurations.
(Vous pourrez également en apprendre davantage sur ces configurations dans la
[référence sur amp-analytics](/docs/reference/extended/amp-analytics.html).)
### Quelles données sont envoyées : l'attribut requests
La valeur `request-name` est utilisée dans la configuration du déclencheur pour déterminer
quelle requête envoyer en réponse à un événement en particulier.
La valeur `request-value` est une URL `https`.
Ces valeurs peuvent inclure des jetons d'espace réservé
pouvant renvoyer à d'autres requêtes ou variables.
[sourcecode:html]
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}",
"event": "https://example.com/analytics?eid=${eventId}&elab=${eventLabel}&acct=${account}"
}
[/sourcecode]
Certains fournisseurs de solutions d'analyse (notamment Google Analytics)
ont déjà fourni une configuration,
que vous utilisez via l'attribut `type`.
Si vous utilisez un fournisseur de solutions d'analyse,
il se peut que vous n'ayez pas besoin d'inclure l'information `requests`.
Reportez-vous à la documentation de votre fournisseur pour savoir
si l'attribut `requests` doit être configuré et, le cas échéant, comment le configurer.
#### Ajout d'une URL de requête : Attribut extraUrlParams
L'attribut [extraUrlParams](https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/amp-analytics.md#extra-url-params)
spécifie des paramètres additionnels à ajouter à la chaîne de requête de l'URL de requête via la convention usuelle « &foo=baz ».
L'exemple `amp-analytics` ajoute un paramètre additionnel <code>cd1</code>
à la requête et définit la valeur de ce paramètre sur « AMP » :
[sourcecode:html]
"extraUrlParams": {
"cd1": "AMP"
}
[/sourcecode]
### Lorsque les données sont envoyées : l'attribut triggers
L'attribut `triggers` indique le moment auquel une requête d'analyse doit être envoyée.
Il contient une paire clé/valeur précisant le nom et la configuration du déclencheur.
Le nom du déclencheur peut être n'importe quelle chaîne composée
de caractères alphanumériques (a-zA-Z0-9).
Par exemple,
le composant `amp-analytics` suivant est configuré pour envoyer une requête à
`https://example.com/analytics` lorsque le document est chargé pour la première fois
et à chaque fois que l'on clique sur la balise `a` :
[sourcecode:html]
"triggers": {
"trackPageview": {
"on": "visible",
"request": "pageview"
},
"trackAnchorClicks": {
"on": "click",
"selector": "a",
"request": "event",
"vars": {
"eventId": "42",
"eventLabel": "clicked on a link"
}
}
}
[/sourcecode]
AMP prend en charge les configurations suivantes pour le déclencheur :
<table>
<thead>
<tr>
<th data-th="Trigger Config" class="col-thirty">Configuration du déclencheur</th>
<th data-th="Description">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Trigger Config"><code>on</code> (obligatoire)</td>
<td data-th="Description">Événement à écouter. Les valeurs valides sont <code>click</code>, <code>scroll</code>, <code>timer</code> et <code>visible</code>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>request</code> (obligatoire)</td>
<td data-th="Description">Nom de la requête à envoyer (tel que spécifié dans les requêtes <a href="/docs/guides/analytics/deep_dive_analytics.html#what-data-gets-sent-requests-attribute"></a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>vars</code></td>
<td data-th="Description">Objet contenant des paires clé/valeur utilisé pour remplacer la valeur <code>vars</code> dans la configuration de premier niveau ou pour spécifier une valeur <code>vars</code> unique à ce déclencheur (voir également <a href="/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering">Ordonnancement de la substitution des variables</a>).</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>selector</code> (obligatoire lorsque <code>on</code> est défini sur <code>click</code>)</td>
<td data-th="Description">Sélecteur CSS utilisé pour définir plus précisément les éléments à suivre. Utilisez la valeur <code>*</code> pour suivre tous les éléments. Cette configuration est utilisée conjointement avec le déclencheur <code>click</code>. Découvrez comment utiliser le sélecteur pour <a href="/docs/guides/analytics/use_cases.html#tracking-page-clicks">suivre les clics sur une page</a> et les <a href="/docs/guides/analytics/use_cases.html#tracking-social-interactions">interactions sociales</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>scrollSpec</code> (obligatoire lorsque <code>on</code> est défini sur <code>scroll</code>)</td>
<td data-th="Description">Définit les conditions en fonction desquelles l'événement <code>scroll</code> est déclenché lorsque l'on fait défiler la page. Cet objet peut contenir les propriétés <code>verticalBoundaries</code> et <code>horizontalBoundaries</code>. Au moins l'une des deux propriétés est obligatoire pour qu'un événement <code>scroll</code> soit déclenché. Les valeurs de chacune des propriétés doivent être des ensembles de nombres contenant les limites pour lesquelles un événement scroll est généré. Voir cet exemple sur le <a href="/docs/guides/analytics/use_cases.html#tracking-scrolling">suivi du défilement</a>.</td>
</tr>
<tr>
<td data-th="Trigger Config"><code>timerSpec</code> (obligatoire lorsque <code>on</code> est défini sur <code>timer</code>)</td>
<td data-th="Description">Définit les conditions en fonction desquelles l'événement <code>timer</code> est déclenché. L'événement timer est déclenché immédiatement, puis à un intervalle spécifié. Cette configuration est utilisée conjointement avec le déclencheur <code>timer</code>.</td>
</tr>
</tbody>
</table>
**Important :** Les déclencheurs d'une configuration dont la priorité est inférieure sont annulés
par les déclencheurs du même nom dont la priorité est supérieure
(voir [Ordonnancement de la substitution des variables](/docs/guides/analytics/deep_dive_analytics.html#variable-substitution-ordering)).
### Comment les données sont envoyées : l'attribut transport
L'attribut `transport` indique comment envoyer une requête.
Les trois modes suivants sont activés par défaut :
<table>
<thead>
<tr>
<th data-th="Transport Method" class="col-thirty">Mode de transport</th>
<th data-th="Description">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="Transport Method"><code>beacon</code></td>
<td data-th="Description">Indique qu'il est possible d'utiliser <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">navigator.sendBeacon</a> pour transmettre la requête. Cela envoie une requête <code>POST</code> avec des identifiants et une section body vide.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>xhrpost</code></td>
<td data-th="Description">Indique qu'il est possible d'utiliser <code>XMLHttpRequest</code> pour transmettre la requête. Cela envoie une requête <code>POST</code> avec des identifiants et une section body vide.</td>
</tr>
<tr>
<td data-th="Transport Method"><code>image</code></td>
<td data-th="Description">Indique que la requête peut être envoyée en générant une balise <code>Image</code>. Cela envoie une requête <code>GET</code>.</td>
</tr>
</tbody>
</table>
Un seul mode de transport est utilisé :
celui qui est activé, autorisé, disponible
et dont la priorité est la plus haute.
La priorité est `beacon` > `xhrpost` > `image`.
Si l'user-agent du client ne prend pas en charge un mode,
c'est le mode suivant dans l'ordre de priorité qui est utilisé.
N'incluez l'attribut `transport` dans votre configuration
que si vous souhaitez limiter les options de transport.
Vous risquez sinon d'arrêter les requêtes.
Dans l'exemple ci-dessous,
`beacon` et `xhrpost` sont définis sur false.
Ils ne seront donc pas utilisés même si leur priorité est supérieure à celle du mode `image`.
Si l'user-agent du client prend en charge le mode `image`,
il sera utilisé. Sinon, aucune requête n'est envoyée.
[sourcecode:html]
'transport': {
'beacon': false,
'xhrpost': false,
'image': true
}
[/sourcecode]
## Ordonnancement de la substitution des variables
AMP renseigne les valeurs des variables dans l'ordre de priorité suivant :
1. Configurations distantes (via `config`).
2. `vars` imbriqué dans un déclencheur dans `triggers`.
3. `vars` au niveau supérieur imbriqué dans `amp-analytics`.
4. Valeurs fournies par la plateforme.
Dans cet exemple, nous avons une configuration distante,
des variables définies au niveau supérieur dans triggers et des valeurs au niveau de la plateforme :
[sourcecode:html]
<amp-analytics config="http://example.com/config.json">
<script type="application/json">
{
"requests": {
"pageview": "https://example.com/analytics?url=${canonicalUrl}&title=${title}&acct=${account}&clientId=${clientId(cid-scope)}",
},
"vars": {
"account": "ABC123",
"title": "Homepage"
},
"triggers": {
"some-event": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "My homepage",
"clientId": "my user"
}
}
}
</script>
</amp-analytics>
[/sourcecode]
Lorsque le même `var` est défini à plusieurs endroits,
l'ordre de priorité de la variable définit sa valeur une fois.
Ainsi, si la configuration distante définit `account` sur UA-XXXXX-Y, comme dans l'exemple ci-dessus,
les valeurs des différentes occurrences de vars sont les suivantes :
<table>
<thead>
<tr>
<th data-th="var" class="col-thirty"><code>var</code></th>
<th data-th="Value">Valeur</th>
<th data-th="Defined By" class="col-thirty">Défini par</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="var"><code>canonicalUrl</code></td>
<td data-th="Value"><code>http://example.com/path/to/the/page</code></td>
<td data-th="Defined By">Plateforme</td>
</tr>
<tr>
<td data-th="var"><code>title</code></td>
<td data-th="Value">My homepage</td>
<td data-th="Defined By">Déclencheur</td>
</tr>
<tr>
<td data-th="var"><code>account</code></td>
<td data-th="Value"><code>UA-XXXXX-Y</code></td>
<td data-th="Defined By">Configuration distante</td>
</tr>
<tr>
<td data-th="var"><code>clientId</code></td>
<td data-th="Value">my user</td>
<td data-th="Defined By">Déclencheur</td>
</tr>
</tbody>
</table>
```
--------------------------------------------------------------------------------
/content/latest/blog/why-amp-caches-exist.md:
--------------------------------------------------------------------------------
```markdown
---
class: post-blog post-detail
type: Blog
$title: Why AMP Caches exist
id: why-amp-caches-exist
author: Paul Bakaus
role: AMP Developer Advocate, Google
origin: "https://amphtml.wordpress.com/2017/01/13/why-amp-caches-exist/amp/"
excerpt: "The following was posted on Medium by Paul Bakaus, AMP Developer Advocate, Google. Caches are a fundamental piece of the Accelerated Mobile Pages (AMP) Project, yet one of the most misunderstood components. Every day, developers ask us why they can’t just get their AMP pages onto some AMP surfaces (e.g. Google) without linking through the […]"
avatar: https://www.gravatar.com/avatar/9a2d68554d8d1655a3fb3e2a50aee909
date_data: 2017-01-13T12:19:43-08:00
$date: January 13, 2017
$parent: /content/latest/list-blog.html
components:
- social-share
---
<div class="amp-wp-article-content">
<p><em>The following was <a href="https://medium.com/@pbakaus/why-amp-caches-exist-cd7938da2456#.u99e695t5" target="_blank">posted on Medium</a> by Paul Bakaus, AMP Developer Advocate, Google.</em></p>
<p><span style="font-weight:400;">Caches are a fundamental piece of the Accelerated Mobile Pages (AMP) Project, yet one of the most misunderstood components. Every day, developers ask us why they can’t just get their AMP pages onto some AMP surfaces (e.g. Google) without linking through the cache. Some worry about the cache model breaking the origin model of the web, others worry about analytics attribution and canonical link sharing, and even others worry about their pages being hosted on servers out of their control. Let’s look at all of these, and understand why the caches exist.</span></p>
<p><span style="font-weight:400;">While AMP Caches introduce some trade-offs, they do work in the user’s favor to ensure a consistently fast and user-friendly experience. The caches are designed to:</span></p>
<ul>
<li style="font-weight:400;"><span style="font-weight:400;">Ensure that all AMP pages are actually valid AMP.</span></li>
<li style="font-weight:400;"><span style="font-weight:400;">Allow AMP pages to be preloaded efficiently and safely.</span></li>
<li style="font-weight:400;"><span style="font-weight:400;">Do a myriad of additional user-beneficial performance optimizations to content.</span></li>
</ul>
<p><span style="font-weight:400;">But first:</span></p>
<h2><span style="font-weight:400;">The Basics: Analytics attribution and link sharing</span></h2>
<p><span style="font-weight:400;">Even though the AMP Cache model doesn’t follow the </span><a href="https://tools.ietf.org/html/rfc6454"><span style="font-weight:400;">origin model</span></a><span style="font-weight:400;"> (serving your page from your own domain), we attribute all traffic to you, the publisher. Through the </span><a href="https://www.ampproject.org/docs/reference/components/amp-analytics"><span style="font-weight:400;"><amp-analytics></span></a><span style="font-weight:400;"> tag, AMP supports a growing number of analytics providers (</span><a href="https://www.ampproject.org/docs/reference/components/amp-analytics#analytics-vendors"><span style="font-weight:400;">26 to date</span></a> and growing<span style="font-weight:400;">!), to make sure you can measure your success and the traffic is correctly attributed.</span></p>
<p><span style="font-weight:400;">When I ask users and developers about why they want to “click-through” to the canonical page from a cached AMP result, the answer is often about link sharing. And granted, it’s annoying to copy a google.com URL instead of the canonical URL. However, the issue isn’t as large of a problem as you’d think: Google amends its cached AMP search results with Schema.org and OpenGraph metadata, so posting the link to any platform that honors these should result in the canonical URL being shared. That being said, there are more opportunities to improve the sharing flow. In native web-views, one could share the canonical directly if the app supports it, and, based on users’ feedback, the team at Google is working on enabling easy access to the canonical URL on all its surfaces.</span></p>
<p><span style="font-weight:400;">With these cleared up, let’s dig a little deeper.</span></p>
<h2><span style="font-weight:400;">When the label says AMP, you get AMP</span></h2>
<p><span style="font-weight:400;">The AMP Project consists of an ecosystem that depends on strict validation, ensuring that very high performance and quality bars are met. One version of a validator can be used during development, but the AMP Cache ensures the validity at the last stage, when presenting content to the user.</span></p>
<p><span style="font-weight:400;">When an AMP page is requested from an AMP Cache for the first time, said cache validates the document first, and won’t offer it to the user if it detects problems. Platforms integrating with AMP (e.g. Bing, Pinterest, Google) can choose to send traffic directly to the AMP page on the origin or optionally to an AMP Cache, but validity can only be guaranteed when served from the cache. </span><b>It ensures that when users see the AMP label, they’ll almost always get a fast and user friendly experience</b><span style="font-weight:400;">. (Unless you find a way to make a slow-but-valid AMP page, which is hard, but not impossible… I’m looking at you, big web fonts).</span></p>
<h2><span style="font-weight:400;">Pre-rendering is a bigger deal than you think</span></h2>
<p><span style="font-weight:400;">If you take anything away from this post, it’s that pre-rendering, especially the variant in AMP, greatly outweighs any speed gains you could theoretically get by hosting directly from an origin server. Even if the origin server is closer to your users, which would shave off a few milliseconds — rare but possible — pre-rendering will almost certainly drive the most impact.</span></p>
<h3><span style="font-weight:400;">Perceived as much faster</span></h3>
<p><span style="font-weight:400;">In fact, pre-rendering can often save you seconds, not milliseconds. The impact of pre-rendering, as opposed to the various other performance optimizations in the AMP JS library, can be pretty dramatic, and contributes largely to the “instant-feel” experience.</span></p>
<h2><img data-attachment-id="919" data-permalink="https://amphtml.wordpress.com/2017/01/13/why-amp-caches-exist/cache_post/" data-orig-file="https://amphtml.files.wordpress.com/2017/01/cache_post.png?w=660" data-orig-size="633,218" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="cache_post" data-image-description="" data-medium-file="https://amphtml.files.wordpress.com/2017/01/cache_post.png?w=660?w=300" data-large-file="https://amphtml.files.wordpress.com/2017/01/cache_post.png?w=660?w=633" class="alignnone size-full wp-image-919" src="https://amphtml.files.wordpress.com/2017/01/cache_post.png?w=660" alt="cache_post" srcset="https://amphtml.files.wordpress.com/2017/01/cache_post.png 633w, https://amphtml.files.wordpress.com/2017/01/cache_post.png?w=150 150w, https://amphtml.files.wordpress.com/2017/01/cache_post.png?w=300 300w" sizes="(max-width: 633px) 100vw, 633px" /></h2>
<h3><span style="font-weight:400;">Very efficient compared to full pre-rendering</span></h3>
<p><span style="font-weight:400;">If that was the whole story, we could just as easily pre-render AMP pages from their origin servers. If we did, we couldn’t guarantee that a page is valid AMP on the origin, and valid AMP is critically important for the custom pre-rendering the AMP JS library provides: Pre-rendering in AMP, as opposed to just pre-rendering an entire page through something like </span><a href="https://en.wikipedia.org/wiki/Link_prefetching"><span style="font-weight:400;">link prefetching</span></a><span style="font-weight:400;">, also limits the use of the users’ bandwidth, CPU and battery!</span></p>
<p><span style="font-weight:400;">Valid AMP documents behave “cooperatively” during the pre-render stage: Only assets in the first viewport get preloaded, and no third-party scripts get executed. This results in a much cheaper, less bandwidth and CPU-intensive preload, allowing platforms to prerender not just the first, but a few of the AMP pages a user will likely click on.</span></p>
<h3><span style="font-weight:400;">Safe to embed</span></h3>
<p><span style="font-weight:400;">Because AMP Caches can’t rely on browser pre-rendering (see the section above), normal navigation from page to page doesn’t work. So in the AMP caching model, a page needs to be opened inline on a platform page. AMP Caches ensure that the requested AMP page can do that safely:</span></p>
<ul>
<li style="font-weight:400;"><span style="font-weight:400;">Validator ensures no </span><a href="https://en.wikipedia.org/wiki/Cross-site_scripting"><span style="font-weight:400;">Cross-Site Scripting</span></a><span style="font-weight:400;"> (XSS) in main document.</span></li>
<li style="font-weight:400;"><span style="font-weight:400;">On top of the validator, the AMP Cache parses and then re-serializes the document in an unambiguous fashion (this means that it does not rely on HTML5 error correction). This ensures that browser parsing bugs and differences cannot lead to XSS.</span></li>
<li style="font-weight:400;"><span style="font-weight:400;">The cache applies a </span><a href="https://developer.chrome.com/extensions/contentSecurityPolicy"><span style="font-weight:400;">Content Security Policy</span></a><span style="font-weight:400;"> (CSP). This provides additional defense-in-depth against XSS attacks.</span></li>
</ul>
<h3><span style="font-weight:400;">Additional privacy</span></h3>
<p><span style="font-weight:400;">In addition, the AMP Caches remove one important potential privacy issue from the pre-render: When you do a search on a content platform preloading AMP pages on the result page, none of the preloaded AMP pages will ever know about the fact that they’ve been preloaded.</span></p>
<p><span style="font-weight:400;">Think about it this way: Say I search for “breakfast burrito”. If you know me well, you know I obviously searched for </span><a href="https://www.youtube.com/watch?v=prPjpwsGiws"><span style="font-weight:400;">Parry Gripp’s song</span></a><span style="font-weight:400;"> with the same name. But the search result page also shows me a couple of AMP search results from fast food chains that sell actual breakfast burritos. For the next month, I wouldn’t want to see actual breakfast burritos everywhere even though I didn’t click on these links (even though…maybe I do…mhh..), and an advertiser wouldn’t want to waste dollars on me for pointless re-marketing ads on all the burritos. Since AMP hides the preload from the publisher of the AMP page and related third parties, it’s a win win scenario for users and advertisers.</span></p>
<h2><span style="font-weight:400;">Auto-optimizations that often result in dramatic speed increase</span></h2>
<p><span style="font-weight:400;">The AMP Cache started out with all of the above, but has since added a number of transformative transformations (heh) to its feature roster. Among those optimizations:</span></p>
<ul>
<li style="font-weight:400;"><span style="font-weight:400;">Consistent, fast and free content delivery network for all content (not just big publishers).</span></li>
<li style="font-weight:400;"><span style="font-weight:400;">Optimizes HTML through measures such as bringing scripts into the ideal order, removing duplicate script tags and removing unnecessary quotes and whitespace.</span></li>
<li style="font-weight:400;"><span style="font-weight:400;">Rewrites JavaScript URLs to have infinite cache time.</span></li>
<li style="font-weight:400;"><a href="https://developers.googleblog.com/2017/01/google-amp-cache-amp-lite-and-need-for.html"><span style="font-weight:400;">Optimizes images</span></a><span style="font-weight:400;"> (a 40% average bandwidth improvement!)</span></li>
</ul>
<p><span style="font-weight:400;">On the image compression side alone, Google, through its cache, is doing lossless (without </span><i><span style="font-weight:400;">any</span></i><span style="font-weight:400;"> visual change, e.g. removes EXIF data) and lossy (without </span><i><span style="font-weight:400;">noticeable</span></i><span style="font-weight:400;"> visual change) compression. In addition, it converts images to WebP for browsers that support it and automatically generates srcset attributes (so-called responsive images) if they’re not already available, generating and showing correctly sized images to each device. </span></p>
<h2><span style="font-weight:400;">Isn’t there a better way of doing this?</span></h2>
<p><span style="font-weight:400;">Look, I hear you. The provider of an AMP Cache is mirroring your content. It’s an important role and comes with great responsibility. If the cache provider were to do something truly stupid, like inserting obnoxious ads into every AMP page, AMP would stop being a viable solution for publishers, and thus wither away.</span></p>
<p><span style="font-weight:400;">Remember, AMP has been created together with publishers, as a means to make the mobile web better for publishers, users and platforms. It’s why the AMP team has released </span><a href="https://github.com/ampproject/amphtml/blob/master/spec/amp-cache-guidelines.md"><span style="font-weight:400;">strict guidelines</span></a><span style="font-weight:400;"> for AMP Caches. To give you two interesting excerpts, the guidelines state that your content needs to provide “a faithful visual and UX reproduction of source document”, and cache providers must pledge that they will keep URLs working indefinitely, even after the cache itself may be decommissioned. These, and many more rules, ensure that a cache doesn’t mess with your content.</span></p>
<p><span style="font-weight:400;">Most importantly, there’s plenty of room for more than one AMP Cache – in fact, Cloudflare </span><a href="https://blog.cloudflare.com/accelerated-mobile/"><span style="font-weight:400;">just announced</span></a><span style="font-weight:400;"> their own! With these </span><a href="https://github.com/ampproject/amphtml/blob/master/spec/amp-cache-guidelines.md"><span style="font-weight:400;">AMP Cache guidelines</span></a><span style="font-weight:400;"> released, other infrastructure companies are welcome to create new AMP Caches, as long as they follow the rules. It’s then up to the platform integrating AMP to pick their favorite cache.</span></p>
<h2><span style="font-weight:400;">From cache to web standards?</span></h2>
<p><span style="font-weight:400;">You just read about all the wins and trade-offs the AMP Caches do to provide an instant-feeling, and user friendly mobile web experience. What if we could get to many of the same awesome optimizations without the trade-offs, and without involving a cache at all?</span></p>
<p><span style="font-weight:400;">Personally, I dream of future, still-to-be-invented web standards that would allow us to get there – to move beyond cache models (like a static layout system to know how a page will look like before any assets are loaded). </span></p>
<p><span style="font-weight:400;">In 2016, we’ve done our first baby steps with the </span><a href="https://timkadlec.com/2016/02/a-standardized-alternative-to-amp/"><span style="font-weight:400;">CPP</span></a><span style="font-weight:400;">, which turned into the </span><a href="https://github.com/WICG/feature-policy"><span style="font-weight:400;">Feature Policy</span></a><span style="font-weight:400;">: A way of saying things like “I disallow document.write on my site, and any third parties in any iframes that get loaded”. More advanced concepts like static layouting and safe prerendering require far-fetching changes to the web platform, but hey – just like forward time travel, it’s not impossible, just very, very difficult <img src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></span></p>
<p><span style="font-weight:400;">Join me in figuring this out by getting in touch on </span><a href="https://twitter.com/pbakaus"><span style="font-weight:400;">Twitter</span></a><span style="font-weight:400;"> or </span><a href="https://docs.google.com/a/google.com/forms/d/e/1FAIpQLSd83J2IZA6cdR6jPwABGsJE8YL4pkypAbKMGgUZZriU7Qu6Tg/viewform?fbzx=4406980310789882877"><span style="font-weight:400;">Slack</span></a><span style="font-weight:400;">, and know that I’ll always have an open ear for your questions, ideas and concerns. Onwards!</span></p>
<p></p><br /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/amphtml.wordpress.com/910/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/amphtml.wordpress.com/910/" /></a> <img alt="" border="0" src="https://pixel.wp.com/b.gif?host=amphtml.wordpress.com&blog=102788268&post=910&subd=amphtml&ref=&feed=1" width="1" height="1" />
</div>
```