1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 'use strict'; 6 7 base.exportTo('base', function() { 8 9 /** 10 * Uses an embedded iframe to measure provided elements without forcing layout 11 * on the main document. You must call attach() on the stick before using it, 12 * and call detach() on it when you are done using it. 13 * @constructor 14 * @extends {Object} 15 */ 16 function MeasuringStick() { 17 this.iframe_ = undefined; 18 } 19 20 MeasuringStick.prototype = { 21 __proto__: Object.prototype, 22 23 /** 24 * Measures the provided element without forcing layout on the main 25 * document. 26 */ 27 measure: function(element) { 28 this.iframe_.contentDocument.body.appendChild(element); 29 var style = this.iframe_.contentWindow.getComputedStyle(element); 30 var width = parseInt(style.width, 10); 31 var height = parseInt(style.height, 10); 32 this.iframe_.contentDocument.body.removeChild(element); 33 return { width: width, height: height }; 34 }, 35 36 attach: function() { 37 var iframe = document.createElement('iframe'); 38 iframe.style.cssText = 39 'position:absolute;width:100%;height:0;border:0;visibility:hidden'; 40 document.body.appendChild(iframe); 41 this.iframe_ = iframe; 42 this.iframe_.contentDocument.body.style.cssText = 43 'padding:0;margin:0;overflow:hidden'; 44 45 var stylesheets = document.querySelectorAll('link[rel=stylesheet]'); 46 for (var i = 0; i < stylesheets.length; i++) { 47 var stylesheet = stylesheets[i]; 48 var link = this.iframe_.contentDocument.createElement('link'); 49 link.rel = 'stylesheet'; 50 link.href = stylesheet.href; 51 this.iframe_.contentDocument.head.appendChild(link); 52 } 53 }, 54 55 detach: function() { 56 document.body.removeChild(this.iframe_); 57 this.iframe_ = undefined; 58 } 59 }; 60 61 return { 62 MeasuringStick: MeasuringStick 63 }; 64 }); 65