Skip to content
This repository was archived by the owner on Oct 8, 2021. It is now read-only.

Commit 6aa578d

Browse files
author
Gabriel Schulhof
committed
View source: Cache stringification result
1 parent 674aa15 commit 6aa578d

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

demos/_assets/js/view-source.js

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,45 @@ function getSnippet( type, selector, source ) {
5353
if ( el.length === 0 && type === "style" ) {
5454
el = source.find( "link[rel='stylesheet']" + selector );
5555
}
56-
text = $( "<div></div>" )
57-
.append( ( "markup" === type ? el : el.contents() ).clone() )
58-
.html();
56+
57+
// Stringify each element and cache the string representation on the element. This helps us
58+
// avoid re-stringifying the element later. This, in turn, prevents us from re-stringifying
59+
// already enhanced elements, such as shared widgets outside the page, when the View Source
60+
// button is in the page, and the elements have already been enhanced when the View Source
61+
// button is created. This assumes, of course, that the first time we stringify an element
62+
// the element is not yet enhanced.
63+
el.each( function( index, singleElement ) {
64+
var whitespace,
65+
single = $( this ),
66+
singleText = single.jqmData( "viewSourceCachedData" );
67+
68+
if ( !singleText ) {
69+
singleText = $( "<div></div>" )
70+
.append( ( "markup" === type ? single : single.contents() ).clone() )
71+
.html();
72+
73+
// If we're dealing with markup, retrieve the initial indentation of the element so
74+
// we get proper indentation in the source view
75+
if ( type === "markup" ) {
76+
if ( this.previousSibling && this.previousSibling.nodeType === 3 ) {
77+
whitespace = $( "<div>" )
78+
.append( $( this.previousSibling ).clone() )
79+
.html()
80+
.match( /\n(\s*)$/ );
81+
if ( whitespace && whitespace.length > 1 ) {
82+
singleText = whitespace[ 1 ] + singleText;
83+
}
84+
}
85+
}
86+
single.jqmData( "viewSourceCachedData", singleText );
87+
}
88+
89+
text = text +
90+
91+
// Separate the text for multiple elements with a newline
92+
( index > 0 ? "\n" : "" ) +
93+
singleText;
94+
});
5995
if ( !text ) {
6096
text = "";
6197
selector = el.attr( "href" ) || el.attr( "src" ) || "";

0 commit comments

Comments
 (0)