从Chrome源码看浏览器如何构建DOM树

时间:2023-03-09 20:43:11
从Chrome源码看浏览器如何构建DOM树

.aligncenter { clear: both; display: block; margin-left: auto; margin-right: auto }
p { font-size: 15px; text-indent: 2em }
#colorbox.crayon-colorbox,#cboxOverlay.crayon-colorbox,.crayon-colorbox #cboxWrapper { position: absolute; top: 0; left: 0; z-index: 9999; overflow: hidden }
#cboxOverlay.crayon-colorbox { position: fixed; width: 100%; height: 100% }
.crayon-colorbox #cboxMiddleLeft,.crayon-colorbox #cboxBottomLeft { clear: left }
.crayon-colorbox #cboxContent { position: relative }
.crayon-colorbox #cboxLoadedContent { overflow: auto }
.crayon-colorbox #cboxTitle { display: none !important }
.crayon-colorbox #cboxLoadingOverlay,.crayon-colorbox #cboxLoadingGraphic { position: absolute; top: 0; left: 0; width: 100%; height: 100% }
.crayon-colorbox #cboxPrevious,.crayon-colorbox #cboxNext,.crayon-colorbox #cboxClose,.crayon-colorbox #cboxSlideshow { cursor: pointer }
.crayon-colorbox .cboxPhoto { float: left; margin: auto; border: 0; display: block; max-width: none }
.crayon-colorbox .cboxIframe { width: 100%; height: 100%; display: block; border: 0 }
#colorbox.crayon-colorbox,.crayon-colorbox #cboxContent,.crayon-colorbox #cboxLoadedContent { }
#cboxOverlay.crayon-colorbox { background: #000 }
#colorbox.crayon-colorbox { outline: 0 }
.crayon-colorbox #cboxContent { margin-top: 20px; background: #000 }
.crayon-colorbox .cboxIframe { background: #fff }
.crayon-colorbox #cboxError { padding: 50px; border: 1px solid #ccc }
.crayon-colorbox #cboxLoadedContent { border: 5px solid #000; background: #fff }
.crayon-colorbox #cboxTitle { position: absolute; top: -20px; left: 0; color: #ccc }
.crayon-colorbox #cboxCurrent { position: absolute; top: -20px; right: 0; color: #ccc }
.crayon-colorbox #cboxPrevious,.crayon-colorbox #cboxNext,.crayon-colorbox #cboxSlideshow,.crayon-colorbox #cboxClose { border: 0; padding: 0; margin: 0; overflow: visible; width: auto; background: 0 }
.crayon-colorbox #cboxPrevious:active,.crayon-colorbox #cboxNext:active,.crayon-colorbox #cboxSlideshow:active,.crayon-colorbox #cboxClose:active { outline: 0 }
.crayon-colorbox #cboxSlideshow { position: absolute; top: -20px; right: 90px; color: #fff }
.crayon-colorbox #cboxContent { margin-top: 0 }
.crayon-colorbox #cboxLoadedContent { border: 0 }
#crayon-main-wrap .form-table th { width: 100px }
#crayon-log { display: none; max-height: 200px; border-color: #dfdfdf; background-color: white; border-width: 1px; border-style: solid; margin: 1px; padding: 3px; overflow: auto; white-space: pre; margin-bottom: 5px }
.crayon-span,.crayon-span-5,.crayon-span-10,.crayon-span-50,.crayon-span-100,.crayon-span-110 { line-height: 24px; display: inline-block }
.crayon-span-5 { min-width: 5px }
.crayon-span-10 { min-width: 10px }
.crayon-span-50 { min-width: 50px }
.crayon-span-100 { min-width: 100px }
.crayon-span-110 { min-width: 117px }
.crayon-span-margin { margin-left: 5px }
#height_mode,#width_mode { min-width: 65px }
.crayon-error { color: #F00 }
.crayon-success { color: #00F }
.crayon-warning { color: #ff8000 }
.crayon-help { min-height: 30px; padding: 5px 10px }
.crayon-help .crayon-help-close,.crayon-help .crayon-help-close:active,.crayon-help .crayon-help-close:hover { text-decoration: none; float: right; color: #000 }
.crayon-help span,.crayon-help a { margin: 0; padding: 0; font-size: 12px }
#crayon-log-text { font: 11px/13px Monaco, "MonacoRegular", "Courier New", monospace }
#crayon-log-controls { float: left; margin-right: 5px }
.crayon-table { font-size: 12px; border: 1px solid #999; padding: 0; margin: 0; margin-top: 12px }
.crayon-table td { vertical-align: top; border-bottom: 1px solid #AAA; padding: 0 6px; margin: 0; background: #EEE }
.crayon-table-light td { background: #f8f8f8 }
.crayon-table-header td { font-weight: bold; background: #CCC }
.crayon-table-last td,.crayon-table tr:last-child td { border: 0 }
#lang-info div { padding: 5px 0 }
.crayon-table .not-parsed { color: #F00 }
.crayon-table .parsed-with-errors { color: #f90 }
.crayon-table .successfully-parsed { color: #77a000 }
#crayon-live-preview,#crayon-log-wrapper { padding: 0; width: 100%; float: left; clear: both }
#crayon-live-preview { float: none; padding: 0 }
#crayon-logo { text-align: center }
#crayon-info,#crayon-info td { border: 0; padding: 0 5px; margin: 0 }
.crayon-admin-button { display: inline-block; text-align: center }
#crayon-subsection-langs-info { margin-top: 5px }
#crayon-theme-editor-admin-buttons { display: inline }
#crayon-theme-editor-admin-buttons .crayon-admin-button { margin-left: 5px }
#crayon-theme-info { display: table; padding: 0; margin: 0; margin-top: 5px }
#crayon-theme-info>div { display: table-cell; vertical-align: middle }
#crayon-theme-info .content * { float: left }
#crayon-theme-info .field { font-weight: bold }
#crayon-theme-info .field,#crayon-theme-info .value { margin-left: 5px }
#crayon-theme-info .description.value { font-style: italic; color: #999 }
#crayon-theme-info .type { text-align: center; min-width: 120px; font-weight: bold; border-right: 1px solid #ccc; padding-right: 5px }
#crayon-theme-info .type.stock { color: #666 }
#crayon-theme-info .type.user { color: #5b9a00 }
#crayon-editor-table td { vertical-align: top }
.small-icon { width: 24px; height: 24px; display: inline-block; margin: 5px 5px 0 0 }
#twitter-icon { background: url("../images/twitter.png") }
#gmail-icon { background: url("../images/google.png") }
#docs-icon { background: url("../images/docs.png") }
#git-icon { background: url("../images/github.png") }
#wp-icon { background: url("../images/wordpress-blue.png") }
#donate-icon { background: url("../images/donate.png"); width: 75px }
#crayon-donate,#crayon-donate input { margin: 0; display: inline; padding: 0 }
#crayon-theme-editor-info a { text-decoration: none !important; font-style: italic !important; color: #666 !important }
#crayon-main-wrap .form-table .note { font-style: italic; color: #999 }
#crayon-change-code-text { width: 400px; height: 300px }
.crayon-syntax { overflow: hidden !important; position: relative !important; text-align: left; direction: ltr !important }
.crayon-syntax div { background: 0; border: 0; padding: 0; margin: 0; text-align: left }
.crayon-syntax.crayon-loading { visibility: hidden }
.crayon-syntax,.crayon-syntax .crayon-main,.crayon-syntax .crayon-toolbar,.crayon-syntax .crayon-info,.crayon-syntax .crayon-plain,.crayon-syntax .crayon-code { width: 100% }
.crayon-syntax .crayon-main,.crayon-syntax .crayon-plain { overflow: auto }
.crayon-syntax,.crayon-syntax .crayon-main,.crayon-syntax .crayon-plain,.crayon-syntax .crayon-table { padding: 0; margin: 0 }
.crayon-syntax-inline { margin: 0 2px; padding: 0 2px }
.crayon-syntax .crayon-table { border: none !important; background: none !important; padding: 0 !important; margin-top: 0 !important; margin-right: 0 !important; margin-bottom: 0 !important; width: auto !important; border-spacing: 0 !important; border-collapse: collapse !important; table-layout: auto !important }
.crayon-syntax .crayon-table td,.crayon-syntax .crayon-table tr { padding: 0 !important; border: none !important; background: 0; vertical-align: top !important; margin: 0 !important }
.crayon-syntax .crayon-invisible { display: none !important }
.crayon-plain-tag { margin-bottom: 12px }
.crayon-popup .crayon-plain { display: block !important; width: 100% !important; height: 100% !important; opacity: 100 !important; position: relative !important }
.crayon-popup-window { background: #fff }
.crayon-syntax .crayon-num { text-align: center; padding: 0 5px; margin: 0 }
.crayon-syntax .crayon-toolbar { position: relative; overflow: hidden; z-index: 4 }
.crayon-syntax .crayon-info { position: absolute; overflow: hidden; display: none; z-index: 3; padding: 0; min-height: 18px; line-height: 18px }
.crayon-syntax .crayon-info div { padding: 2px !important; text-align: center }
.crayon-syntax .crayon-toolbar span { padding: 0 4px !important }
.crayon-syntax .crayon-toolbar .crayon-button { display: inline; float: left !important; position: relative; width: 24px; background-repeat: no-repeat; line-height: 15px; border: 0; text-decoration: none }
.crayon-toolbar .crayon-button,.crayon-toolbar .crayon-button:hover,.crayon-toolbar .crayon-button.crayon-pressed:hover { background-position: 0 center }
.crayon-toolbar .crayon-button.crayon-pressed,.crayon-toolbar .crayon-button:active,.crayon-toolbar .crayon-button.crayon-pressed:active { background-position: -24px 0 }
.crayon-toolbar .crayon-button.crayon-popup-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-popup-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-popup-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 0 }
.crayon-toolbar .crayon-button.crayon-copy-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-copy-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-copy-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -16px }
.crayon-toolbar .crayon-button.crayon-nums-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-nums-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-nums-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -32px }
.crayon-toolbar .crayon-button.crayon-plain-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-plain-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-plain-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -48px }
.crayon-toolbar .crayon-button.crayon-mixed-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-mixed-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-mixed-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -64px }
.crayon-toolbar .crayon-button.crayon-minimize .crayon-button-icon { background-position: 0 -80px; background-color: transparent !important }
.crayon-toolbar .crayon-button.crayon-expand-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-expand-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-expand-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -96px }
.crayon-toolbar .crayon-button.crayon-wrap-button .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-wrap-button:hover .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-wrap-button.crayon-pressed:hover .crayon-button-icon { background-position: 0 -112px }
.crayon-toolbar .crayon-button.crayon-popup-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-popup-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-popup-button.crayon-pressed:active .crayon-button-icon { background-position: -24px 0 }
.crayon-toolbar .crayon-button.crayon-copy-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-copy-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-copy-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -16px }
.crayon-toolbar .crayon-button.crayon-nums-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-nums-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-nums-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -32px }
.crayon-toolbar .crayon-button.crayon-plain-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-plain-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-plain-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -48px }
.crayon-toolbar .crayon-button.crayon-mixed-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-mixed-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-mixed-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -64px }
.crayon-toolbar .crayon-button.crayon-minimize .crayon-button-icon { background-position: -24px -80px; background-color: transparent !important }
.crayon-toolbar .crayon-button.crayon-expand-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-expand-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-expand-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -96px }
.crayon-toolbar .crayon-button.crayon-wrap-button.crayon-pressed .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-wrap-button:active .crayon-button-icon,.crayon-toolbar .crayon-button.crayon-wrap-button.crayon-pressed:active .crayon-button-icon { background-position: -24px -112px }
.crayon-syntax .crayon-toolbar .crayon-language { padding-right: 8px !important }
.crayon-syntax .crayon-title,.crayon-syntax .crayon-language { float: left }
.crayon-main::-webkit-scrollbar,.crayon-plain::-webkit-scrollbar { height: 6px; overflow: visible; width: 6px; background: #EEE }
.crayon-main::-webkit-scrollbar-thumb,.crayon-plain::-webkit-scrollbar-thumb { background-color: #CCC; border: 1px solid #AAA; min-height: 8px; padding: 0; border-width: 1px }
.crayon-main::-webkit-scrollbar-button,.crayon-plain::-webkit-scrollbar-button { height: 0; width: 0; padding: 0 }
.crayon-main::-webkit-scrollbar-track,.crayon-plain::-webkit-scrollbar-track { border-width: 0 0 0 4px; border: 1px solid #BBB; border-right: 0; border-bottom: 0 }
.crayon-main::-webkit-scrollbar-corner,.crayon-plain::-webkit-scrollbar-corner { background: #EEE }
.crayon-main::-webkit-scrollbar-thumb:hover,.crayon-plain::-webkit-scrollbar-thumb:hover { background: #AAA; border: 1px solid #777 }
.crayon-syntax .crayon-pre,.crayon-syntax pre { color: #000; white-space: pre; margin: 0; padding: 0; overflow: visible; background: none !important; border: none !important }
.crayon-syntax .crayon-line { padding: 0 5px }
.crayon-syntax.crayon-wrapped .crayon-line { white-space: pre-wrap !important; height: auto }
.crayon-syntax-inline .crayon-pre,.crayon-syntax-inline pre { white-space: normal }
.crayon-syntax-inline-nowrap .crayon-pre,.crayon-syntax-inline-nowrap pre { white-space: pre }
.crayon-syntax { font-family: Monaco, "MonacoRegular", "Courier New", monospace; font-weight: 500 }
.crayon-syntax .crayon-toolbar *::selection,.crayon-syntax .crayon-nums *::selection { background: transparent }
.crayon-table .crayon-nums-content { white-space: nowrap }
.crayon-syntax .crayon-num,.crayon-syntax .crayon-pre .crayon-line,.crayon-syntax .crayon-toolbar *,.crayon-syntax .crayon-pre * { font-family: inherit; font-size: inherit !important; line-height: inherit !important; font-weight: inherit !important; height: inherit }
.crayon-syntax .crayon-toolbar .crayon-button .crayon-button-icon { background-image: url("../images/toolbar/buttons.png"); height: 16px !important; width: 100%; position: absolute; left: 0; top: 50%; margin-top: -8px }
.crayon-syntax .crayon-toolbar .crayon-tools { position: absolute; right: 0 }
.crayon-syntax.crayon-expanded { position: absolute !important; margin: 0 !important }
.crayon-syntax.crayon-expanded .crayon-main { overflow: hidden !important }
.crayon-placeholder { width: 100% !important }
.crayon-toolbar-visible .crayon-toolbar { position: relative !important; margin-top: 0 !important; display: block !important }
.crayon-syntax.crayon-expanded .crayon-toolbar .crayon-tools { position: relative; right: auto; float: left !important }
.crayon-syntax .crayon-plain-wrap { height: auto !important; padding: 0 !important; margin: 0 !important }
.crayon-syntax .crayon-plain { width: 100%; height: 100%; position: absolute; opacity: 0; padding: 0 5px; margin: 0; border: 0; white-space: pre; overflow: auto; color: #000; background: #FFF }
.crayon-wrapped .crayon-plain { white-space: pre-wrap }
.bbp-body .crayon-syntax { clear: none !important }
.crayon-minimized .crayon-toolbar { cursor: pointer }
.crayon-minimized .crayon-plain-wrap,.crayon-minimized .crayon-main,.crayon-minimized .crayon-toolbar .crayon-tools * { display: none !important }
.crayon-minimized .crayon-toolbar .crayon-tools .crayon-minimize { display: block !important }
.crayon-minimized .crayon-toolbar { position: relative !important }
.crayon-syntax.crayon-minimized .crayon-toolbar { border-bottom: none !important }
.crayon-te *,#crayon-te-bar-content { font-family: "Lucida Grande", Arial, sans-serif !important; font-size: 12px }
.crayon-te input[type="text"],.crayon-te textarea { background: #f9f9f9; border: 1px solid #CCC; padding: 2px 4px; border-width: 1px; border-style: solid }
.crayon-te #crayon-code { font-family: monospace !important }
#crayon-te-content,#crayon-te-table { width: 100%; height: auto !important }
#crayon-range,#crayon-mark { width: 100px }
#crayon-te-table th,#crayon-te-table td { vertical-align: top; text-align: left }
.rtl #crayon-te-table th,.rtl #crayon-te-table td { text-align: right }
#crayon-te-table .crayon-tr-center td,#crayon-te-table .crayon-tr-center th { vertical-align: middle }
#crayon-te-table .crayon-nowrap { white-space: nowrap }
#crayon-te-bar { position: absolute; top: 0; left: 0; width: 100% }
#crayon-te-bar-content { border: 1px solid #666; border-bottom: 0; height: 26px; line-height: 25px; padding: 0 8px; padding-right: 0; background-color: #222; color: #cfcfcf }
#crayon-te-bar-content a { line-height: 25px; padding: 5px 10px; color: #DDD; font-weight: bold; text-decoration: none !important }
#crayon-te-bar-content a:hover { color: #FFF }
.crayon-te-seperator { color: #666; margin: 0; padding: 0 }
#crayon-te-bar-block { height: 34px; width: 100% }
#crayon-te-title { float: left }
#crayon-te-controls { float: right }
#crayon-url-th { vertical-align: top !important; padding-top: 5px }
.crayon-te-heading { font-size: 14px; font-weight: bold }
#crayon-te-settings-info { text-align: center }
.crayon-te-section { font-weight: bold; padding: 0 10px }
#crayon-te-sub-section { margin-left: 10px }
#crayon-te-sub-section .crayon-te-section { font-weight: normal; padding: 0 }
#crayon-code { height: 200px; white-space: pre }
#crayon-code,#crayon-url { width: 555px !important }
.crayon-disabled { background: #EEE !important }
.qt_crayon_highlight { background-image: linear-gradient(bottom,#daf2ff,white) !important }
.qt_crayon_highlight:hover { background: #ddebf2 !important }
.crayon-tag-editor-button-wrapper { display: inline-block }
.mce_crayon_tinymce { padding: 0 !important; margin: 2px 3px !important }
.mce-i-crayon_tinymce,.mce_crayon_tinymce { background: url("../images/crayon_tinymce.png") 0 0 !important }
a.mce_crayon_tinymce { background-position: 2px 0 !important }
.wp_themeSkin .mceButtonEnabled:hover span.mce_crayon_tinymce,.wp_themeSkin .mceButtonActive span.mce_crayon_tinymce { background-position: -20px 0 }
.wp_themeSkin span.mce_crayon_tinymce { background: none !important }
#crayon-te-table { margin-top: 26px; padding: 10px; border-collapse: separate !important; border-spacing: 2px !important }
#crayon-te-table th { width: 100px }
#crayon-te-clear { color: #666; background-color: #f4f4f4; border: 1px solid #CCC; margin-left: 8px }
#crayon-title { width: 360px }
#TB_window.crayon-te-ajax { overflow: auto !important }
#TB_window.crayon-te-ajax,#TB_window.crayon-te-ajax #TB_ajaxContent,#TB_window.crayon-te-ajax #TB_title { width: 680px !important }
#TB_window.crayon-te-ajax #TB_ajaxContent { padding: 0 !important; margin: 0 !important; width: 100% !important; height: auto !important; margin-top: 28px !important }
#TB_window.crayon-te-ajax #TB_title { position: fixed !important }
#TB_window.crayon-te-ajax #TB_title .crayon-te-submit { margin-top: 3px !important; float: right !important }
#TB_window.crayon-te-ajax a { color: #2587e2; text-decoration: none }
#TB_window.crayon-te-ajax a:hover { color: #499ce9 }
.crayon-te-quote { background: #DDD; padding: 0 2px }
#crayon-te-submit-wrapper { display: none }
#crayon-te-clear { display: none; margin: 0; margin-top: 10px }
.crayon-syntax-pre { background: red; white-space: pre; overflow: auto; display: block }
.crayon-question { padding: 1px 4px !important; text-decoration: none !important; color: #83b3cb !important; height: 15px !important; width: 15px !important }
.crayon-question:hover { background: #83b3cb !important; color: white !important; height: 15px !important; width: 15px !important }
.crayon-setting-changed,.crayon-setting-selected { background: #fffaad !important }
.crayon-question:hover { color: white; background: #a6d6ef }
#crayon-te-warning { display: none }
.crayon-te-info { padding: 5px !important; margin: 2px 0 !important }
#crayon-te-submit { margin-bottom: 5px }
.crayon-theme-github { margin-bottom: 25px !important; border: 1px solid #dedede !important; background-color: #f8f8ff !important; font-size: 100% !important; line-height: 130% !important }
.crayon-theme-github .crayon-toolbar { border-bottom: 1px solid #dedede !important; background-color: #eee !important }
.crayon-theme-github .crayon-toolbar .crayon-language,.crayon-theme-github .crayon-toolbar .crayon-title { font-size: 80% !important; color: #666 !important }
.crayon-theme-github .crayon-table .crayon-nums { background-color: #eee !important }
.crayon-theme-github .crayon-table .crayon-nums-content { padding-top: 5px !important; padding-bottom: 3px !important }
.crayon-theme-github .crayon-table .crayon-num { min-width: 1.2em !important; border-right: 1px solid #dedede !important; text-align: right !important; color: #aaa !important }
.crayon-theme-github .crayon-pre { padding-top: 5px !important; padding-bottom: 3px !important }
.crayon-theme-github .crayon-marked-line { background: #fffee2 !important }
.crayon-theme-github .crayon-marked-num { color: #1561ac !important; background: #b3d3f4 !important; border-width: 1px !important; border-color: #5999d9 !important }
.crayon-theme-github .crayon-pre .crayon-c { color: #999 !important; font-style: italic !important }
.crayon-theme-github .crayon-pre .crayon-s { color: #d14 !important }
.crayon-theme-github .crayon-pre .crayon-p { color: #b85c00 !important }
.crayon-theme-github .crayon-pre .crayon-ta { color: #FF0000 !important }
.crayon-theme-github .crayon-pre .crayon-k { color: teal !important }
.crayon-theme-github .crayon-pre .crayon-st { color: #000 !important; font-weight: bold !important }
.crayon-theme-github .crayon-pre .crayon-r { color: #000 !important; font-weight: bold !important }
.crayon-theme-github .crayon-pre .crayon-t { color: #800080 !important; font-weight: bold !important }
.crayon-theme-github .crayon-pre .crayon-m { color: #800080 !important }
.crayon-theme-github .crayon-pre .crayon-i { color: #000 !important }
.crayon-theme-github .crayon-pre .crayon-e { color: teal !important }
.crayon-theme-github .crayon-pre .crayon-v { color: #002D7A !important }
.crayon-theme-github .crayon-pre .crayon-cn { color: #099 !important }
.crayon-theme-github .crayon-pre .crayon-o { color: #006fe0 !important }
.crayon-theme-github .crayon-pre .crayon-sy { color: #333 !important }
.crayon-theme-github .crayon-pre .crayon-n { color: #666 !important; font-style: italic }
.crayon-theme-github .crayon-pre .crayon-f { color: #999 !important }
.crayon-theme-github .crayon-pre .crayon-h { color: #006fe0 !important }
.crayon-syntax .crayon-pre,.crayon-syntax pre { white-space: initial }
img { margin-top: 10px; margin-bottom: 10px }
img { margin-top: 10px; margin-bottom: 10px }

这几天下了Chrome的源码,安装了一个debug版的Chromium研究了一下,虽然很多地方都一知半解,但是还是有一点收获,将在这篇文章介绍DOM树是如何构建的,看了本文应该可以回答以下问题:

  1. IE用的是Trident内核,Safari用的是Webkit,Chrome用的是Blink,到底什么是内核,它们的区别是什么?
  2. 如果没有声明<!DOCTYPE html>会造成什么影响?
  3. 浏览器如何处理自定义的标签,如写一个<data></data>?
  4. 查DOM的过程是怎么样的?

先说一下,怎么安装一个可以debug的Chrome

1. 从源码安装Chrome

为了可以打断点debug,必须得从头编译(编译的时候带上debug参数)。所以要下载源码,Chrome把最新的代码更新到了Chromium的工程,是完全开源的,你可以把它整一个git工程下载下来。Chromium的下载安装可参考它的文档, 这里把一些关键点说一下,以Mac为例。你需要先下载它的安装脚本工具,然后下载源码:

Shell

fetch chromium --no-history
1
fetch chromium--no-history

–no-history的作用是不把整个git工程下载下来,那个实在是太大了。或者是直接执行git clone:

Shell

git clone https://chromium.googlesource.com/chromium/src
1
git clonehttps://chromium.googlesource.com/chromium/src

这个就是整一个git工程,下载下来有6.48GB(那时)。博主就是用的这样的方式,如果下载到最后提示出错了:

fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
1
2
3
fatal:The remote endhung up unexpectedly
fatal:early EOF
fatal:index-pack failed

可以这样解决:

JavaScript

git config --global core.compression 0
git clone --depth 1 https://chromium.googlesource.com/chromium/src
1
2
git config--globalcore.compression0
git clone--depth1 https://chromium.googlesource.com/chromium/src

就不用重头开始clone,因为实在太大、太耗时了。

下载好之后生成build的文件:

Shell

gn gen out/gn --ide=xcode
1
gn gen out/gn--ide=xcode

–ide=xcode是为了能够使用苹果的XCode进行可视化进行调试。gn命令要下载Chrome的devtools包,文档里面有说明。

装备就绪之后就可以进行编译了:

Shell

ninja -C out/gn chrome
1
ninja-Cout/gn chrome

在笔者的电脑上编译了3个小时,firfox的源码需要编译7、8个小时,所以相对来说已经快了很多,同时没报错,一次就过,相当顺利。编译组装好了之后,会在out/gn目录生成Chromium的可执行文件,具体路径是在:

out/gn/Chromium.app/Contents/MacOS/Chromium
1
out/gn/Chromium.app/Contents/MacOS/Chromium

运行这个就可以打开Chromium了:

从Chrome源码看浏览器如何构建DOM树

那么怎么在可视化的XCode里面进行debug呢?

2. 在XCode里面进行Debug

在上面生成build文件的同时,会生成XCode的工程文件:sources.xcodeproj,具体路径是在:

out/gn/sources.xcodeproj
1
out/gn/sources.xcodeproj

双击这个文件,打开XCode,在上面的菜单栏里面点击Debug -> AttachToProcess -> Chromium,要先打开Chrome,才能在列表里面看到Chrome的进程。然后小试牛刀,打个断点试试,看会不会跑进来:

在左边的目录树,打开chrome/browser/devtools/devtools_protocol.cc这个文件,然后在这个文件的ParseCommand函数里面打一个断点,按照字面理解这个函数应该是解析控制台的命令。打开Chrome的控制台,输入一条命令,例如:new Date(),按回车可以看到断点生效了:

从Chrome源码看浏览器如何构建DOM树

通过观察变量值,可以看到刚刚敲进去的命令。这就说明了我们安装成功,并且可以通过可视化的方式进行调试。

但是我们要debug页面渲染过程,Chrome的blink框架使用多进程技术,每打开一个tab都会新开一个进程,按上面的方式是debug不了构建DOM过程的,从Chromium的文档可以查到,需要在启动的时候带上一个参数:

Shell

Chromium --renderer-startup-dialog
1
Chromium--renderer-startup-dialog

Chrom的启动进程就会绪塞,并且提示它的渲染进程ID:

[7339:775:0102/210122.254760:ERROR:child_process.cc(145)] Renderer (7339) paused waiting for debugger to attach. Send SIGUSR1 to unpause.

7339就是它的渲染进程id,在XCode里面点 Debug -> AttachToProcess By Id or Name -> 填入id -> 确定,attach之后,Chrome进程就会恢复,然后就可以开始调试渲染页面的过程了。

在content/renderer/render_view_impl.cc这个文件的1093行RenderViewImpl::Create函数里面打个断点,按照上面的方式,重新启动Chrome,在命令行带上某个html文件的路径,为了打开Chrome的时候就会同时打开这个文件,方便调试。执行完之后就可以看到断点生效了。可以说render_view_impl.cc这个文件是第一个具体开始渲染页面的文件——它会初始化页面的一些默认设置,如字体大小、默认的viewport等,响应关闭页面、OrientationChange等事件,而在它再往上的层主要是一些负责通信的类。

3. Chrome建DOM源码分析

先画出构建DOM的几个关键的类的UML图,如下所示:

从Chrome源码看浏览器如何构建DOM树

第一个类HTMLDocumentParser负责解析html文本为tokens,一个token就是一个标签文本的序列化,并借助HTMLTreeBuilder对这些tokens分类处理,根据不同的标签类型、在文档不同位置,调用HTMLConstructionSite不同的函数构建DOM树。而HTMLConstructionSite借助一个工厂类对不同类型的标签创建不同的html元素,并建立起它们的父子兄弟关系,其中它有一个m_document的成员变量,这个变量就是这棵树的根结点,也是js里面的window.document对象。

为作说明,用一个简单的html文件一步步看这个DOM树是如何建立起来的:

XHTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<h1 class="title">demo</h1>
<input value="hello">
</div>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <div>
        <h1 class="title">demo</h1>
        <input value="hello">
    </div>
</body>
</html>

然后按照上面第2点提到debug的方法,打开Chromium并开始debug:

Shell

chromium ~/demo.html --renderer-startup-dialog
1
chromium~/demo.html--renderer-startup-dialog

我们先来研究一下Chrome的加载和解析机制

1. 加载机制

以发http请求去加载html文本做为我们分析的第一步,在此之前的一些初始化就不考虑了。Chrome是在DocumentLoader这个类里面的startLoadingMainResource函数里去加载url返回的数据,如访问一个网站则返回html文本:

DocumentLoader::startLoadingMainResource

C++

FetchRequest fetchRequest(<strong>m_request</strong>, FetchInitiatorTypeNames::document,
mainResourceLoadOptions);
m_mainResource =
RawResource::fetchMainResource(fetchRequest, fetcher(), m_substituteData);
1
2
3
4
  FetchRequest fetchRequest(<strong>m_request</strong>,FetchInitiatorTypeNames::document,
                            mainResourceLoadOptions);
  m_mainResource=
      RawResource::fetchMainResource(fetchRequest,fetcher(),m_substituteData);

把m_request打印出来,在这个函数里面加一行代码:

C++

LOG(INFO) << "request url is: " << m_request.url().getString()
1
LOG(INFO)<<"request url is: "<<m_request.url().getString()

并重新编译Chrome运行,控制台输出:

[22731:775:0107/224014.494114:INFO:DocumentLoader.cpp(719)] request url is: “file:///Users/yincheng/demo.html”

可以看到,这个url确实是我们传进的参数。

发请求后,每次收到的数据块,会通过Blink封装的IPC进程间通信,触发DocumentLoader的dataReceived函数,里面会去调它commitData函数,开始处理具体业务逻辑:

C++

void DocumentLoader::commitData(const char* bytes, size_t length) {
ensureWriter(m_response.mimeType());

if (length)
m_dataReceived = true;

m_writer->addData(bytes, length);
}

1
2
3
4
5
6
7
8
voidDocumentLoader::commitData(constchar*bytes,size_t length){
  ensureWriter(m_response.mimeType());
  if(length)
    m_dataReceived=true;
  m_writer->addData(bytes,length);
}

这个函数关键行是最2行和第7行,ensureWriter这个函数会去初始化上面画的UML图的解析器HTMLDocumentParser (Parser),并实例化document对象,这些实例都通过实例m_writer去带动的。也就是说,writer会去实例化Parser,然后第7行writer传递数据给Parser去解析。

检查一下收到的数据bytes是什么东西:从Chrome源码看浏览器如何构建DOM树

可以看到bytes就是请求返回的html文本。

在ensureWriter函数里面有个判断:

C++

void DocumentLoader::ensureWriter(const AtomicString& mimeType,
const KURL& overridingURL) {
if (m_writer)
return;

}

1
2
3
4
5
6
voidDocumentLoader::ensureWriter(constAtomicString&mimeType,
                                  constKURL&overridingURL){
  if(m_writer)
    return;
}

如果m_writer已经初始化过了,则直接返回。也就是说Parser和document只会初始化一次。

在上面的addData函数里面,会启动一条线程执行Parser的任务:

C++

if (!m_haveBackgroundParser)
startBackgroundParser();
1
2
if(!m_haveBackgroundParser)
      startBackgroundParser();

并把数据传递给这条线程进行解析,Parser一旦收到数据就会序列成tokens,再构建DOM树。

2. 构建tokens

这里我们只要关注序列化后的token是什么东西就好了,为此,写了一个函数,把tokens的一些关键信息打印出来:

C++

String getTokenInfo(){
String tokenInfo = "";
tokenInfo = "tagName: " + this->m_name + "|type: " + getType() + "|attr:" + getAttributes() + "|text: " + this->m_data;
return tokenInfo;
}
1
2
3
4
5
  StringgetTokenInfo(){
    StringtokenInfo="";
    tokenInfo="tagName: "+this->m_name+"|type: "+getType()+"|attr:"+getAttributes()+"|text: "+this->m_data;
    returntokenInfo;
  }

打印出来的结果:

tagName: html |type: DOCTYPE |attr: |text: "
tagName: |type: Character |attr: |text: \n"
tagName: html |type: startTag |attr: |text: "
tagName: |type: Character |attr: |text: \n"
tagName: head |type: startTag |attr: |text: "
tagName: |type: Character |attr: |text: \n "
tagName: meta |type: startTag |attr:charset=utf-8 |text: "
tagName: |type: Character |attr: |text: \n"
tagName: head |type: EndTag |attr: |text: "
tagName: |type: Character |attr: |text: \n"
tagName: body |type: startTag |attr: |text: "
tagName: |type: Character |attr: |text: \n "
tagName: div |type: startTag |attr: |text: "
tagName: |type: Character |attr: |text: \n "
tagName: h1 |type: startTag |attr:class=title |text: "
tagName: |type: Character |attr: |text: demo"
tagName: h1 |type: EndTag |attr: |text: "
tagName: |type: Character |attr: |text: \n "
tagName: input |type: startTag |attr:value=hello |text: "
tagName: |type: Character |attr: |text: \n "
tagName: div |type: EndTag |attr: |text: "
tagName: |type: Character |attr: |text: \n"
tagName: body |type: EndTag |attr: |text: "
tagName: |type: Character |attr: |text: \n"
tagName: html |type: EndTag |attr: |text: "
tagName: |type: Character |attr: |text: \n"
tagName: |type: EndOfFile |attr: |text: "
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
tagName: html  |type: DOCTYPE   |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n"
tagName: html  |type: startTag  |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n"
tagName: head  |type: startTag  |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n    "
tagName: meta  |type: startTag  |attr:charset=utf-8 |text: "
tagName:       |type: Character |attr:              |text: \n"
tagName: head  |type: EndTag    |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n"
tagName: body  |type: startTag  |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n    "
tagName: div   |type: startTag  |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n        "
tagName: h1    |type: startTag  |attr:class=title   |text: "
tagName:       |type: Character |attr:              |text: demo"
tagName: h1    |type: EndTag    |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n        "
tagName: input |type: startTag  |attr:value=hello   |text: "
tagName:       |type: Character |attr:              |text: \n    "
tagName: div   |type: EndTag    |attr:              |text: "
tagName:       |type: Character |attr:              |text:     \n"
tagName: body  |type: EndTag    |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n"
tagName: html  |type: EndTag    |attr:              |text: "
tagName:       |type: Character |attr:              |text: \n"
tagName:       |type: EndOfFile |attr:              |text: "

这些内容有标签名、类型、属性和innerText,标签之间的文本(换行和空白)也会被当作一个标签处理。Chrome总共定义了7种标签类型:

C++

enum TokenType {
Uninitialized,
DOCTYPE,
StartTag,
EndTag,
Comment,
Character,
EndOfFile,
};
1
2
3
4
5
6
7
8
9
  enumTokenType{
    Uninitialized,
    DOCTYPE,
    StartTag,
    EndTag,
    Comment,
    Character,
    EndOfFile,
  };

有了一个根结点document和一些格式化好的tokens,就可以构建dom树了。

3. 构建DOM树

(1)DOM结点

在研究这个过程之前,先来看一下一个DOM结点的数据结构是怎么样的。以p标签HTMLParagraphElement为例,画出它的UML图,如下所示:

从Chrome源码看浏览器如何构建DOM树

Node是最顶层的父类,它有三个指针,两个指针分别指向它的前一个结点和后一个结点,一个指针指向它的父结点;

ContainerNode继承于Node,添加了两个指针,一个指向第一个子元素,另一个指向最后一个子元素;

Element又添加了获取dom结点属性、clientWidth、scrollTop等函数

HTMLElement又继续添加了Translate等控制,最后一级的子类HTMLParagraphElement只有一个创建的函数,但是它继承了所有父类的属性。

需要提到的是每个Node都组合了一个treeScope,这个treeScope记录了它属于哪个document(一个页面可能会嵌入iframe)。

构建DOM最关键的步骤应该是建立起每个结点的父子兄弟关系,即上面提到的成员指针的指向。

到这里我们可以先回答上面提出的第一个问题,什么是浏览器内核

(2)浏览器内核

浏览器内核也叫渲染引擎,上面已经看到了Chrome是如何实例化一个P标签的,而从firefox的源码里面P标签的依赖关系是这样的:

从Chrome源码看浏览器如何构建DOM树

在代码实现上和Chrome没有任何关系。这就好像W3C出了道题,firefox给了一个解法,取名为Gecko,Safari也给了自己的答案,取名Webkit,Chrome觉得Safari的解法比较好直接拿过来用,又结合自身的基础又封装了一层,取名Blink。由于W3C出的这道题“开放性”比较大,出的时间比较晚,导致各家实现各有花样。

明白了这点后,继续DOM构建。下面开始不再说Chrome,叫Webkit或者Blink应该更准确一点

(3)处理开始步骤

Webkit把tokens序列好之后,传递给构建的线程。在HTMLDocumentParser::processTokenizedChunkFromBackgroundParser的这个函数里面会做一个循环,把解析好的tokens做一个遍历,依次调constructTreeFromCompactHTMLToken进行处理。

根据上面的输出,最开始处理的第一个token是docType的那个:

"tagName: html |type: DOCTYPE |attr: |text: "
1
"tagName: html  |type: DOCTYPE   |attr:              |text: "

在那个函数里面,首先Parser会调TreeBuilder的函数:

C++

m_treeBuilder->constructTree(&token);
1
m_treeBuilder->constructTree(&token);

然后在TreeBuilder里面根据token的类型做不同的处理:

C++

void HTMLTreeBuilder::processToken(AtomicHTMLToken* token) {
if (token->type() == HTMLToken::Character) {
processCharacter(token);
return;
}

switch (token->type()) {
case HTMLToken::DOCTYPE:
processDoctypeToken(token);
break;
case HTMLToken::StartTag:
processStartTag(token);
break;
case HTMLToken::EndTag:
processEndTag(token);
break;
//othercode
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
voidHTMLTreeBuilder::processToken(AtomicHTMLToken*token){
  if(token->type()==HTMLToken::Character){
    processCharacter(token);
    return;
  }
  switch(token->type()){
    caseHTMLToken::DOCTYPE:
      processDoctypeToken(token);
      break;
    caseHTMLToken::StartTag:
      processStartTag(token);
      break;
    caseHTMLToken::EndTag:
      processEndTag(token);
      break;
    //othercode
  }
}

它会对不同类型的结点做相应处理,从上往下依次是文本节点、doctype节点、开标签、闭标签。doctype这个结点比较特殊,单独作为一种类型处理

(3)DOCType处理

在Parser处理doctype的函数里面调了HTMLConstructionSite的插入doctype的函数:

C++

void HTMLTreeBuilder::processDoctypeToken(AtomicHTMLToken* token) {
m_tree.insertDoctype(token);
setInsertionMode(BeforeHTMLMode);
}
1
2
3
4
voidHTMLTreeBuilder::processDoctypeToken(AtomicHTMLToken*token){
    m_tree.insertDoctype(token);
    setInsertionMode(BeforeHTMLMode);
}

在这个函数里面,它会先创建一个doctype的结点,再创建插dom的task,并设置文档类型:

C++

void HTMLConstructionSite::insertDoctype(AtomicHTMLToken* token) {
//const String& publicId = ...
//const String& systemId = ...
DocumentType* doctype =
DocumentType::create(m_document, token->name(), publicId, systemId); //创建DOCType结点
attachLater(m_attachmentRoot, doctype); //创建插DOM的task
setCompatibilityModeFromDoctype(token->name(), publicId, systemId); //设置文档类型
}
1
2
3
4
5
6
7
8
voidHTMLConstructionSite::insertDoctype(AtomicHTMLToken*token){
  //const String& publicId = ...
  //const String& systemId = ...
  DocumentType*doctype=
      DocumentType::create(m_document,token->name(),publicId,systemId);//创建DOCType结点
  attachLater(m_attachmentRoot,doctype);  //创建插DOM的task
  setCompatibilityModeFromDoctype(token->name(),publicId,systemId);//设置文档类型
}

我们来看一下不同的doctype对文档类型的设置有什么影响,如下:

C++

// Check for Quirks Mode.
if (name != "html" ) {
setCompatibilityMode(Document::QuirksMode);
return;
}
1
2
3
4
5
  // Check for Quirks Mode.
  if(name!="html"){
    setCompatibilityMode(Document::QuirksMode);
    return;
  }

如果tagName不是html,那么文档类型将会是怪异模式,以下两种就会是怪异模式:

<!DOCType svg>
<!DOCType math>
1
2
<!DOCType svg>
<!DOCType math>

而常用的html4写法:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
1
2
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

在源码里面这个将是有限怪异模式:

有限怪异模式

C++

// Check for Limited Quirks Mode.
if (!systemId.isEmpty() &&
publicId.startsWith("-//W3C//DTD HTML 4.01 Transitional//",
TextCaseASCIIInsensitive))) {
setCompatibilityMode(Document::LimitedQuirksMode);
return;
}
1
2
3
4
5
6
7
  // Check for Limited Quirks Mode.
  if(!systemId.isEmpty()&&
       publicId.startsWith("-//W3C//DTD HTML 4.01 Transitional//",
                           TextCaseASCIIInsensitive))){
    setCompatibilityMode(Document::LimitedQuirksMode);
    return;
  }

上面的systemId就是”http://www.w3.org/TR/html4/loose.dtd”,它不是空的,所以判断成立。而如果systemId为空,则它将是怪异模式。如果既不是怪异模式,也不是有限怪异模式,那么它就是标准模式:

标准模式

C++

// Otherwise we are No Quirks Mode.
setCompatibilityMode(Document::NoQuirksMode);
1
2
  // Otherwise we are No Quirks Mode.
  setCompatibilityMode(Document::NoQuirksMode);

常用的html5的写法就是标准模式,如果连DOCType声明也没有呢?那么会默认设置为怪异模式:

默认为怪异模式

C++

void HTMLConstructionSite::setDefaultCompatibilityMode() {
setCompatibilityMode(Document::QuirksMode);
}
1
2
3
voidHTMLConstructionSite::setDefaultCompatibilityMode(){
  setCompatibilityMode(Document::QuirksMode);
}

这些模式有什么区别,从源码注释可窥探一二:

三种模式的区别

C++

// There are three possible compatibility modes:
// Quirks - quirks mode emulates WinIE and NS4. CSS parsing is also relaxed in
// this mode, e.g., unit types can be omitted from numbers.
// Limited Quirks - This mode is identical to no-quirks mode except for its
// treatment of line-height in the inline box model.
// No Quirks - no quirks apply. Web pages will obey the specifications to the
// letter.
1
2
3
4
5
6
7
  // There are three possible compatibility modes:
  // Quirks - quirks mode emulates WinIE and NS4. CSS parsing is also relaxed in
  // this mode, e.g., unit types can be omitted from numbers.
  // Limited Quirks - This mode is identical to no-quirks mode except for its
  // treatment of line-height in the inline box model.
  // No Quirks - no quirks apply. Web pages will obey the specifications to the
  // letter.

大意是说,怪异模式会模拟IE,同时CSS解析会比较宽松,例如数字单位可以省略,而有限怪异模式和标准模式的唯一区别在于在于对inline元素的行高处理不一样。标准模式将会让页面遵守文档规定。

怪异模式下的input和textarea的默认盒模型将会变成border-box:

从Chrome源码看浏览器如何构建DOM树

标准模式下的文档高度是实际内容的高度:

从Chrome源码看浏览器如何构建DOM树

而在怪异模式下的文档高度是窗口可视域的高度:

从Chrome源码看浏览器如何构建DOM树

在有限怪异模式下,div里面的图片下方不会留空白,如下图左所示;而在标准模式下td下方会留点空白,如下图右所示:

XHTML

<div><img src="test.jpg" style="height:100px"></div>
1
<div><img src="test.jpg"style="height:100px"></div>
从Chrome源码看浏览器如何构建DOM树从Chrome源码看浏览器如何构建DOM树

这个空白是div的行高撑起来的,当把div的行高设置成0的时候,就没有下面的空白了。在怪异模和有限怪异模式下,为了计算行内子元素的最小高度,一个块级元素的行高必须被忽略。

这里的叙述虽然跟解读源码没有直接的关系(我们还没解读到CSS处理),但是很有必要提一下。

接下来我们开始正式说明DOM构建

(4)开标签处理

下一个遇到的开标签是<html>标签,处理这个标签的任务应该是实例化一个HTMLHtmlElement元素,然后把它的父元素指向document。Webkit源码里面使用了一个m_attachmentRoot的变量记录attach的根结点,初始化HTMLConstructionSite也会初始化这个变量,值为document:

C++

HTMLConstructionSite::HTMLConstructionSite(
Document& document)
: m_document(&document),
m_attachmentRoot(document)) {
}
1
2
3
4
5
HTMLConstructionSite::HTMLConstructionSite(
    Document&document)
    :m_document(&document),
      m_attachmentRoot(document)){
}

所以html结点的父结点就是document,实际的操作过程是这样的:

C++

void HTMLConstructionSite::insertHTMLHtmlStartTagBeforeHTML(AtomicHTMLToken* token) {
HTMLHtmlElement* element = HTMLHtmlElement::create(*m_document);
attachLater(m_attachmentRoot, element);
m_openElements.pushHTMLHtmlElement(HTMLStackItem::create(element, token));
executeQueuedTasks();
}
1
2
3
4
5
6
voidHTMLConstructionSite::insertHTMLHtmlStartTagBeforeHTML(AtomicHTMLToken*token){
  HTMLHtmlElement*element=HTMLHtmlElement::create(*m_document);
  attachLater(m_attachmentRoot,element);
  m_openElements.pushHTMLHtmlElement(HTMLStackItem::create(element,token));
  executeQueuedTasks();
}

第二行先创建一个html结点,第三行把它加到一个任务队列里面,传递两个参数,第一个参数是父结点,第二个参数是当前结点,第五行执行队列里面的任务。代码第四行会把它压到一个栈里面,这个栈存放了未遇到闭标签的所有开标签。

第三行attachLater是如何建立一个task的:

C++

void HTMLConstructionSite::attachLater(ContainerNode* parent,
Node* child,
bool selfClosing) {
HTMLConstructionSiteTask task(HTMLConstructionSiteTask::Insert);
task.parent = parent;
task.child = child;
task.selfClosing = selfClosing;

// Add as a sibling of the parent if we have reached the maximum depth
// allowed.
if (m_openElements.stackDepth() > maximumHTMLParserDOMTreeDepth &&
task.parent->parentNode())
task.parent = task.parent->parentNode();

queueTask(task);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
voidHTMLConstructionSite::attachLater(ContainerNode*parent,
                                       Node*child,
                                       boolselfClosing){
  HTMLConstructionSiteTask task(HTMLConstructionSiteTask::Insert);
  task.parent=parent;
  task.child=child;
  task.selfClosing=selfClosing;
  // Add as a sibling of the parent if we have reached the maximum depth
  // allowed.
  if(m_openElements.stackDepth()>maximumHTMLParserDOMTreeDepth&&
      task.parent->parentNode())
    task.parent=task.parent->parentNode();
  queueTask(task);
}

代码逻辑比较简单,比较有趣的是发现DOM树有一个最大的深度:maximumHTMLParserDOMTreeDepth,超过这个最大深度就会把它子元素当作父无素的同级节点,这个最大值是多少呢?512:

C++

static const unsigned maximumHTMLParserDOMTreeDepth = 512;
1
staticconstunsignedmaximumHTMLParserDOMTreeDepth=512;

我们重点关注executeQueuedTasks干了些什么,它会根据task的类型执行不同的操作,由于本次是insert的,它会去执行一个插入的函数:

C++

void ContainerNode::parserAppendChild(Node* newChild) {
if (!checkParserAcceptChild(*newChild))
return;
AdoptAndAppendChild()(*this, *newChild, nullptr);
}
notifyNodeInserted(*newChild, ChildrenChangeSourceParser);
}
1
2
3
4
5
6
7
voidContainerNode::parserAppendChild(Node*newChild){
  if(!checkParserAcceptChild(*newChild))
    return;
    AdoptAndAppendChild()(*this,*newChild,nullptr);
  }
  notifyNodeInserted(*newChild,ChildrenChangeSourceParser);
}

在插入里面它会先去检查父元素是否支持子元素,如果不支持,则直接返回,就像video标签不支持子元素。然后再去调具体的插入:

C++

void ContainerNode::appendChildCommon(Node& child) {
child.setParentOrShadowHostNode(this);
if (m_lastChild) {
child.setPreviousSibling(m_lastChild);
m_lastChild->setNextSibling(&child);
} else {
setFirstChild(&child);
}
setLastChild(&child);
}
1
2
3
4
5
6
7
8
9
10
voidContainerNode::appendChildCommon(Node&child){
  child.setParentOrShadowHostNode(this);
  if(m_lastChild){
    child.setPreviousSibling(m_lastChild);
    m_lastChild->setNextSibling(&child);
  }else{
    setFirstChild(&child);
  }
  setLastChild(&child);
}

上面代码第二行,设置子元素的父结点,也就是会把html结点的父结点指向document,然后如果没有lastChild,会将这个子元素作为firstChild,由于上面已经有一个docype的子结点了,所以已经有lastChild了,因此会把这个子元素的previousSibling指向老的lastChild,老的lastChild的nexSibling指向它。最后倒数第二行再把子元素设置为当前ContainerNode(即document)的lastChild。这样就建立起了html结点的父子兄弟关系。

可以看到,借助上一次的m_lastChild建立起了兄弟关系

这个时候你可能会有一个问题,为什么要用一个task队列存放将要插入的结点呢,而不是直接插入呢?一个原因放到task里面方便统一处理,并且有些task可能不能立即执行,要先存起来。不过在我们这个案例里面都是存完后下一步就执行了。

当遇到head标签的token时,也是先创建一个head结点,然后再创建一个task,插到队列里面:

C++

void HTMLConstructionSite::insertHTMLHeadElement(AtomicHTMLToken* token) {
m_head = HTMLStackItem::create(createHTMLElement(token), token);
attachLater(currentNode(), m_head->element());
m_openElements.pushHTMLHeadElement(m_head);
}
1
2
3
4
5
voidHTMLConstructionSite::insertHTMLHeadElement(AtomicHTMLToken*token){
  m_head=HTMLStackItem::create(createHTMLElement(token),token);
  attachLater(currentNode(),m_head->element());
  m_openElements.pushHTMLHeadElement(m_head);
}

attachLater传参的第一个参数为父结点,这个currentNode为开标签栈里面的最顶的元素:

C++

ContainerNode* currentNode() const {
return m_openElements.topNode();
}
1
2
3
ContainerNode*currentNode()const{
    returnm_openElements.topNode();
}

我们刚刚把html元素压了进去,则栈顶元素为html元素,所以head的父结点就为html。所以每当遇到一个开标签时,就把它压起来,下一次再遇到一个开标签时,它的父元素就是上一个开标签。

所以,初步可以看到,借助一个栈建立起了父子关系

而当遇到一个闭标签呢?

(5)处理闭标签

当遇到一个闭标签时,会把栈里面的元素一直pop出来,直到pop到第一个和它标签名字一样的:

C++

m_tree.openElements()->popUntilPopped(token->name());
1
m_tree.openElements()->popUntilPopped(token->name());

我们第一个遇到的是闭标签是head标签,它会把开的head标签pop出来,栈里面就剩下html元素了,所以当再遇到body时,html元素就是body的父元素了。

这个是栈的一个典型应用。

以下面的html为例来研究压栈和出栈的过程:

XHTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"></meta>
</head>
<body>
<div>
<p><b>hello</b></p>
<p>demo</p>
</div>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"></meta>
</head>
<body>
    <div>
        <p><b>hello</b></p>
        <p>demo</p>
    </div>
</body>
</html>

把push和pop打印出来是这样的:

push "HTML" m_stackDepth = 1
push "HEAD" m_stackDepth = 2
pop "HEAD" m_stackDepth = 1
push "BODY" m_stackDepth = 2
push "DIV" m_stackDepth = 3
push "P" m_stackDepth = 4
push "B" m_stackDepth = 5
pop "B" m_stackDepth = 4
pop "P" m_stackDepth = 3
push "P" m_stackDepth = 4
pop "P" m_stackDepth = 3
pop "DIV" m_stackDepth = 2
"tagName: body |type: EndTag |attr: |text: "
"tagName: html |type: EndTag |attr: |text: "
1
2
3
4
5
6
7
8
9
10
11
12
13
14
push"HTML"m_stackDepth=1
push"HEAD"m_stackDepth=2
pop"HEAD"m_stackDepth=1
push"BODY"m_stackDepth=2
push"DIV"m_stackDepth=3
push"P"m_stackDepth=4
push"B"m_stackDepth=5
pop"B"m_stackDepth=4
pop"P"m_stackDepth=3
push"P"m_stackDepth=4
pop"P"m_stackDepth=3
pop"DIV"m_stackDepth=2
"tagName: body  |type: EndTag    |attr:              |text: "
"tagName: html  |type: EndTag    |attr:              |text: "

这个过程确实和上面的描述一致,遇到一个闭标签就把一次的开标签pop出来。

并且可以发现遇到body闭标签后,并不会把body给pop出来,因为如果body闭标签后面又再写了标签的话,就会自动当成body的子元素。

假设上面的b标签的闭标签忘记写了,又会发生什么:

XHTML

<p><b>hello</p>
1
<p><b>hello</p>

打印出来的结果是这样的:

push "P" m_stackDepth = 4
push "B" m_stackDepth = 5
"tagName: p |type: EndTag |attr: |text: "
pop "B" m_stackDepth = 4
pop "P" m_stackDepth = 3
push "B" m_stackDepth = 4
push "P" m_stackDepth = 5
pop "P" m_stackDepth = 4
pop "B" m_stackDepth = 3
pop "DIV" m_stackDepth = 2
push "B" m_stackDepth = 3
1
2
3
4
5
6
7
8
9
10
11
push"P"m_stackDepth=4
push"B"m_stackDepth=5
"tagName: p     |type: EndTag    |attr:              |text: "
pop"B"m_stackDepth=4
pop"P"m_stackDepth=3
push"B"m_stackDepth=4
push"P"m_stackDepth=5
pop"P"m_stackDepth=4
pop"B"m_stackDepth=3
pop"DIV"m_stackDepth=2
push"B"m_stackDepth=3

同样地,在上面第3行,遇到P闭标签时,会把所有的开标签pop出来,直到遇到P标签。不同的是后续的过程中会不断地插入b标签,最后渲染的页面结构:

从Chrome源码看浏览器如何构建DOM树

因为b等带有格式化的标签会特殊处理,遇到一个开标签时会它们放到一个列表里面:

C++

// a, b, big, code, em, font, i, nobr, s, small, strike, strong, tt, and u.
m_activeFormattingElements.append(currentElementRecord()->stackItem());
1
2
  // a, b, big, code, em, font, i, nobr, s, small, strike, strong, tt, and u.
  m_activeFormattingElements.append(currentElementRecord()->stackItem());

遇到一个闭标签时,又会从这个列表里面删掉。每处理一个新标签时就会进行检查和这个列表和栈里的开标签是否对应,如果不对应则会reconstruct:重新插入一个开标签。因此b就不断地被重新插入,直到遇到下一个b的闭标签为止。

如果上面少写的是一个span,那么渲染之后的结果是正常的:

从Chrome源码看浏览器如何构建DOM树

而对于文本节点是实例化了Text的对象,这里不再展开讨论。

(6)自定义标签的处理

在浏览器里面可以看到,自定义标签默认不会有任何的样式,并且它默认是一个行内元素:

从Chrome源码看浏览器如何构建DOM树

初步观察它和span标签的表现是一样的:

从Chrome源码看浏览器如何构建DOM树

在blink的源码里面,不认识的标签默认会被实例化成一个HTMLUnknownElement,这个类对外提供了一个create函数,这和HTMLSpanElement是一样的,只有一个create函数,并且大家都是继承于HTMLElement。并且创建span标签的时候和unknown一样,并没有做特殊处理,直接调的create。所以从本质上来说,可以把自定义的标签当作一个span看待。然后你可以再设置display: block改成块级元素之类的。

但是你可以用js定义一个自定义标签,定义它的属性等,Webkit会去读它的定义:

C++

// "4. Let definition be the result of looking up a custom element ..." etc.
CustomElementDefinition* definition =
m_isParsingFragment ? nullptr
: lookUpCustomElementDefinition(document, token);
1
2
3
4
  // "4. Let definition be the result of looking up a custom element ..." etc.
  CustomElementDefinition*definition=
      m_isParsingFragment?nullptr
                          :lookUpCustomElementDefinition(document,token);

例如给自定义标签创建一个原生属性:

XHTML

<high-school country="China">NO. 2 high school</high-school>
1
<high-school country="China">NO. 2 high school</high-school>

上面定义了一个country,为了可以直接获取这个属性:

JavaScript

console.log(document.getElementsByTagName("high-school")[0].country);
1
console.log(document.getElementsByTagName("high-school")[0].country);

注册一个自定义标签:

JavaScript

window.customElements.define("high-school", HighSchoolElement);
1
window.customElements.define("high-school",HighSchoolElement);

这个HighSchoolElement继承于HTMLElement:

JavaScript

class HighSchoolElement extends HTMLElement{
constructor(){
super();
this._country = null;
}
get country(){
return this._country;
}
set country(country){
this.setAttribute("country", _country);
}
static get observedAttributes() {
return ["country"];
}
attributeChangedCallback(name, oldValue, newValue) {
this._country = newValue;
this._updateRender(name, oldValue, newValue);
}
_updateRender(name, oldValue, newValue){
console.log(name + " change from " + oldValue + " " + newValue);
}
}
1
2
3
4
5
6
7
8
9
10
11
classHighSchoolElementextendsHTMLElement{
    constructor(){
        super();
        this._country=null;
    }
    get country(){
        returnthis._country;
    }
    set country(country){
        this.setAttribute("country",_country);
    }

就可以直接取到contry这个属性,而不用通过getAttribute的函数,并且可以在属性发生变化时更新元素的渲染,改变color等。详见Custom Elements – W3C.

通过这种方式创建的,它就不是一个HTMLUnknownElement了。blink通过V8引擎把js的构造函数转化成C++的函数,实例化一个HTMLElement的对象。

最后再来看查DOM的过程

4. 查DOM过程

(1)按ID查找

在页面添加一个script:

JavaScript

<script>document.getElementById("text")</script>
1
<script>document.getElementById("text")</script>

Chrome的V8引擎把js代码层层转化,最后会调:

C++

DocumentV8Internal::getElementByIdMethodForMainWorld(info);
1
DocumentV8Internal::getElementByIdMethodForMainWorld(info);

而这个函数又会调TreeScope的getElementById的函数,TreeScope存储了一个m_map的哈希map,这个map以标签id字符串作为key值,Element为value值,我们可以把这个map打印出来:

C++

Map::iterator it = m_map.begin();
while(it != m_map.end()){
LOG(INFO) << it->key << " " << it->value->element->tagName();
++it;
}
1
2
3
4
5
Map::iterator it=m_map.begin();
while(it!=m_map.end()){
    LOG(INFO)<<it->key<<" "<<it->value->element->tagName();
    ++it;
}

html结构是这样的:

C++

<div class="user" id="id-yin">
<p id="id-name" class="important">yin</p>
<p id="id-age">20</p>
<p id="id-sex">mail</p>
</div>
1
2
3
4
5
<div class="user"id="id-yin">
    <pid="id-name"class="important">yin</p>
    <pid="id-age">20</p>
    <pid="id-sex">mail</p>
</div>

打印出来的结果为:

"id-age" "P"
"id-sex" "P"
"id-name" "P"
"id-yin" "DIV"
1
2
3
4
"id-age""P"
"id-sex""P"
"id-name""P"
"id-yin""DIV"

可以看到, 这个m_map把页面所有有id的标签都存了进来。由于map的查找时间复杂度为O(1),所以使用ID选择器可以说是最快的。

再来看一下类选择器:

(2)类选择器

js如下:

JavaScript

var users = document.getElementsByClassName("user");
users.length;
1
2
varusers=document.getElementsByClassName("user");
users.length;

在执行第一行的时候,Webkit返回了一个ClassCollection的列表:

C++

return new ClassCollection(rootNode, classNames);
1
returnnewClassCollection(rootNode,classNames);

而这个列表并不是去查DOM获取的,它只是记录了className作为标志。这与我们的认知是一致的,这种HTMLCollection的数据结构都是在使用的时候才去查DOM,所以在上面第二行去获取它的length,就会触发它的查DOM,在nodeCount这个函数里面执行:

C++

NodeType* currentNode = collection.traverseToFirst();
unsigned currentIndex = 0;
while (currentNode) {
m_cachedList.push_back(currentNode);
currentNode = collection.traverseForwardToOffset(
currentIndex + 1, *currentNode, currentIndex);
}
1
2
3
4
5
6
7
  NodeType*currentNode=collection.traverseToFirst();
  unsignedcurrentIndex=0;
  while(currentNode){
    m_cachedList.push_back(currentNode);
    currentNode=collection.traverseForwardToOffset(
        currentIndex+1,*currentNode,currentIndex);
  }

第一行先获取符合collection条件的第一个结点,然后不断获取下一个符合条件的结点,直到null,并把它存到一个cachedList里面,下次再获取这个collection的东西时便不用再重复查DOM,只要cached仍然是有效的:

C++

if (this->isCachedNodeCountValid())
return this->cachedNodeCount();
1
2
  if(this->isCachedNodeCountValid())
    returnthis->cachedNodeCount();

怎么样找到有效的节点呢:

C++

ElementType* element = Traversal<ElementType>::firstWithin(current);
while (element && !isMatch(*element))
element = Traversal<ElementType>::next(*element, &current, isMatch);
return element;
1
2
3
4
  ElementType*element=Traversal<ElementType>::firstWithin(current);
  while(element&&!isMatch(*element))
    element=Traversal<ElementType>::next(*element,&current,isMatch);
  returnelement;

第一行先获取第一个节点,如果它没有match,则继续next,直到找到符合条件或者空为止。我们的重点在于,它是怎么遍历的,如何next获取下一个节点,核心代码:

C++

if (current.hasChildren())
return current.firstChild();
if (current == stayWithin)
return 0;
if (current.nextSibling())
return current.nextSibling();
return nextAncestorSibling(current, stayWithin);
1
2
3
4
5
6
7
  if(current.hasChildren())
    returncurrent.firstChild();
  if(current==stayWithin)
    return0;
  if(current.nextSibling())
    returncurrent.nextSibling();
  returnnextAncestorSibling(current,stayWithin);

第一行先判断当前节点有没有子元素,如果有的话返回它的第一个子元素,如果当前节点没有子元素,并且这个节点就是开始找的根元素(document.getElement,则为document),则说明没有下一个元素了,直接返回0/null。如果这个节点不是根元素了(例如已经到了子元素这一层了),那么看它有没有相邻元素,如果有则返回下一下相邻元素,如果相邻无素也没有了,因为它是一个叶子结点(没有子元素),说明它已经到了最深的一层,并且是当前层的最后一个叶子结点,那就返回它的父元素的下个相邻节点。可以看出这是一个深度优先的查找

(3)querySelector

a)先来看下selector为一个id时发生了什么:

JavaScript

document.querySelector("#id-name");
1
document.querySelector("#id-name");

它会调ContainerNode的querySelecotr函数:

C++

SelectorQuery* selectorQuery = document().selectorQueryCache().add(
selectors, document(), exceptionState);

return selectorQuery->queryFirst(*this);

1
2
3
4
SelectorQuery*selectorQuery=document().selectorQueryCache().add(
      selectors,document(),exceptionState);
returnselectorQuery->queryFirst(*this);

先把输入的selector字符串序列化成一个selectorQuery,然后再queryFirst,通过打断点可以发现,它最后会调的TreeScope的getElementById:

C++

rootNode.treeScope().getElementById(idToMatch);
1
rootNode.treeScope().getElementById(idToMatch);
b)如果selector为一个class:

JavaScript

document.querySelector(".user");
1
document.querySelector(".user");

它会从document开始遍历:

C++

for (Element& element : ElementTraversal::descendantsOf(rootNode)) {
if (element.hasClass() && element.classNames().contains(className)) {
SelectorQueryTrait::appendElement(output, element);
if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
return;
}
}
1
2
3
4
5
6
7
  for(Element&element:ElementTraversal::descendantsOf(rootNode)){
    if(element.hasClass()&&element.classNames().contains(className)){
      SelectorQueryTrait::appendElement(output,element);
      if(SelectorQueryTrait::shouldOnlyMatchFirstElement)
        return;
    }
  }

我们重点查看它是怎么遍历,即第一行的for循环。表面上看它好像把所有的元素取出来然后做个循环,其实不然,它是重载++操作符:

C++

void operator++() { m_current = TraversalNext::next(*m_current, m_root); }
1
voidoperator++(){m_current=TraversalNext::next(*m_current,m_root);}

只要我们看下next是怎么操作的就可以得知它是怎么遍历,而这个next跟上面的讲解class时是一样的。不一样的是match条件判断是:有className,并且className列表里面包含这个class,如上面代码第二行。

c)复杂选择器

例如写两个class:

JavaScript

document.querySelector(".user .important");
1
document.querySelector(".user .important");

最终也会转成一个遍历,只是判断是否match的条件不一样:

C++

for (Element& element : ElementTraversal::descendantsOf(*traverseRoot)) {
if (selectorMatches(selector, element, rootNode)) {
SelectorQueryTrait::appendElement(output, element);
if (SelectorQueryTrait::shouldOnlyMatchFirstElement)
return;
}
}
1
2
3
4
5
6
7
  for(Element&element:ElementTraversal::descendantsOf(*traverseRoot)){
    if(selectorMatches(selector,element,rootNode)){
      SelectorQueryTrait::appendElement(output,element);
      if(SelectorQueryTrait::shouldOnlyMatchFirstElement)
        return;
    }
  }

怎么判断是否match比较复杂,这里不再展开讨论。

同时在源码可以看到,如果是怪异模式,会调一个executeSlow的查询,并且判断match条件也不一样。不过遍历是一样的。

查看源码确实是一件很费时费力的工作,但是通过一番探索,能够了解浏览器的一些内在机制,至少已经可以回答上面提出来的几个问题。Webkit/Blink通过借助一个栈,结合开闭标签,一步步构建DOM树,并且重点讨论了DOCType的标签、自定义标签的处理。最后以讨论了查DOM的几种的几种情况。

通过上面的分析,对页面渲染的第一步构建DOM已经有了一个基础的了解。

Post Views: 0