I am working on a Chrome Extension, and I wanted to know if there was a way to know the amount of data which has been downloaded while loading a page.
For example, if the user activates the extension, and goes on Google.com, I want to show him the size of the page: google.com.
Is there a way to do this?
Thanks!
There are a multitude of ways you could determine the size of a page using just javascript.
You could manually calculate the size of the page by counting the ammount of characters in the page and in scripts. The example script bellow calculates the size of an ascii encoded html doc (so not including pictures, scripts from urls, ect). I'm not too sure how accurate or fast this is, so don't quote me on it.
Example script:
var html=document.getElementsByTagName('HTML')[0].outerHTML,//get all html as string
sizeKB=a.length/1024;//assuming the page is encoded in ascii, each char is one byte, 1024 bytes = 1 kb
For determining size of images, this question could help: Determining image file size + dimensions via Javascript?
You could load the results using another service like google's pagespeed insights or pingdom. You could try to load the services in an iframe in your background page and use content scripts to input the url and extract the site's statistics and send them to the popup. I'm sure plenty of other services could help you do the same with ajax calls although I don't know of any.
Using ajax and jquery, you could determine the size of all the assets in the page and add them together: Get size of file requested via ajax . Used correctly, this could fetch all of the files from the catch, so it wouldn't use more of the network. But it might be a bit slow for pages with a lot of non-inline scripts, stylesheets, and images
Using the chrome.webrequest api, you could get the header 'Content-Length' to determine the file size. I haven't tested this script also, so tell me how this works. Make sure to have a fallback if the header is missing!
Example script:
chrome.webRequest.onHeadersReceived.addListener(
function(details){
var fileSize;
details.responseHeaders.forEach(function(v,i,a){
if(v.name == 'Content-Length')
fileSize = v.value;
});
if(!fileSize)//if Content-Length header is missing fall back to another method of calculating file size
fallBackGetFileSize(details);
},
{urls: ["http://*/*"]},["responseHeaders"]);
Related
I can't seem to find a way to display the size of a file in JavaScript in a terminal simulator. (I'm very new to JavaScript)
I've tried these:
https://bitexperts.com/Question/Detail/3316/determine-file-size-in-javascript-without-downloading-a-file
Ajax - Get size of file before downloading
My expected results were to get the byte size but nothing happens.
I'm not able to show any error messages (if there were any) as I am on my school laptop and they blocked Inspect Element.
The output needs to be displayed on the "terminal" itself and it must be strictly JavaScript.
Thanks!
Edit 1:
These are the "terminal" files to make it easier than making files based on snippets that are the whole source. The commands are located at js/terminal.html. The main area we need to pay attention to is Line 144.
I would post it in snippets but I'd make this question 20x the size it is. It's based on Andrew Barfield's HTML5 Terminal
If the server supports HEAD, you can try to use that. However, there's no guarantee that the Content-Length header is returned even if HEAD requests are supported!
Run the below code in a console from stackoverflow and you'll see the size of HTML for their home page without downloading the full page. (Note that StackOverflow no longer provides a content-length header)
fetch('/', {method: 'HEAD'}).then((result) => {
console.log(result.headers.get("content-length"))
})
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD
The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method.
I can't seem to find a way to display the size of a file in JavaScript in a terminal simulator. (I'm very new to JavaScript)
I've tried these:
https://bitexperts.com/Question/Detail/3316/determine-file-size-in-javascript-without-downloading-a-file
Ajax - Get size of file before downloading
My expected results were to get the byte size but nothing happens.
I'm not able to show any error messages (if there were any) as I am on my school laptop and they blocked Inspect Element.
The output needs to be displayed on the "terminal" itself and it must be strictly JavaScript.
Thanks!
Edit 1:
These are the "terminal" files to make it easier than making files based on snippets that are the whole source. The commands are located at js/terminal.html. The main area we need to pay attention to is Line 144.
I would post it in snippets but I'd make this question 20x the size it is. It's based on Andrew Barfield's HTML5 Terminal
If the server supports HEAD, you can try to use that. However, there's no guarantee that the Content-Length header is returned even if HEAD requests are supported!
Run the below code in a console from stackoverflow and you'll see the size of HTML for their home page without downloading the full page. (Note that StackOverflow no longer provides a content-length header)
fetch('/', {method: 'HEAD'}).then((result) => {
console.log(result.headers.get("content-length"))
})
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD
The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method.
I hope questions from beginners are acceptable. I don't mind studying, but based on research so far, I'm not sure where to even begin........
I'm in need of a script that can fit into a small URI space (around 1,000 characters or less) that will rapidly update itself with information parsed by a server script (lsl/mono served by a meta-verse object over http).
The target browser is the built in media viewer of the Second Life viewer (Mozilla based). The parsed html will come from an LSL/mono script. I am attempting to display the resulting html on a primitive inside the Second Life meta-verse (which basically just turns the prim face into a kind of UV projected browser window) at an update resolution from 0.2 to 0.5 seconds.
I gather that I need something like ajax to constantly ping a serving object for the refreshed dynamic information and update a section in the initial URI? I'm at a loss as to how to set this up.
Already Tried:
I've tried simply putting my small bit of html in the URI itself and having the meta-verse's mono/lsl script force a browser update, and this works to some degree, but forcing a media refresh via such a script is throttled to a reliable refresh resolution of around 2 seconds. I really need the refresh to be fully client side instead...at a resolution of more like 0.2 seconds, as the information is used to update a moving vehicle's digital dash instruments.
Already Tried:
Just using a meta based refresh in the URI. Either I did it wrong, or it just doesn't work. Would such a method support a resolution of less than a second anyway?
Also attempted using script examples about ajax from this web site, and while they give good example code, they don't show how to set up the headers and such in the browser to use whatever libraries they're speaking of (it's assumed at the level of those threads the reader knows what libraries they're talking about and how to set them up)...so none of that works for me at this point.
The server script parses a simple bit of dynamically refreshed html formatted text. It could all be dumped into a single div area on each refresh pass.
Example of html that requires rapid parsing:
<body bgcolor="black">
<font size="7" color="cyan"><center>
Throttle: 50%<br>
Speed: 40<br>
Bearing: 100, 100, 1000<hr="red">
HP: 200 - Kills: 3<br>
Damage Dealt: 1000
</center></body>
Or if it's more efficient, it could be dumped as simple variable updates for a more advanced script that only change 'the numbers' in a table? But I have no idea how to do that either.
I think I have a pretty good understanding on how to get the server side scripts to parse the required html I wish to display. I'm just at a total loss on how to set up a URI that will ask for it every 0.2 seconds from the client-side...and avoid pulling that information from a 'cache' rather than the actual target url.
If interpret Question correctly , try utilizing XMLHttpRequest
var js = 'data:text/html;charset=utf-8,<html><script>(function r(){var x=new XMLHttpRequest();x.open("GET","https://gist.githubusercontent.com/anonymous/27e432abdb3c506aaa04/raw/109eb3da644a4bbc4aaa4d10ed286471a31b9655/update.html",true);x.onload=function(){document.write(x.responseText);setTimeout(function(){console.log(r)},200)};x.send()}())</script></html>';
431 characters
// note, `console.log(r)` called at `x.onload` instead of `r()` ,
// at stacksnippets ; to prevent recursive call to `r` , multiple requests , here
var js = 'data:text/html;charset=utf-8,%3Chtml%3E%3Cscript%3E(function%20r()%7Bvar%20x%3Dnew%20XMLHttpRequest()%3Bx.open(%22GET%22%2C%22https%3A%2F%2Fgist.githubusercontent.com%2Fanonymous%2F27e432abdb3c506aaa04%2Fraw%2F109eb3da644a4bbc4aaa4d10ed286471a31b9655%2Fupdate.html%22%2Ctrue)%3Bx.onload%3Dfunction()%7Bdocument.write(x.responseText)%3BsetTimeout(function()%7Bconsole.log(r)%7D%2C200)%7D%3Bx.send()%7D())%3C%2Fscript%3E%3C%2Fhtml%3E';
location.href = js;
Is there a reason PNG and JPG images would be embedded in a JavaScript file like this:
// Template/Image data
var LOGO = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADgAAAA4 etc";
var BACKGROUND = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIA etc";
If I remove these portions and call files stored on a server instead, will there be a performance penalty or something? The only thing I can think of is Apache serving extra requests for those images, but I'm not even sure it works that way. Is there anything else?
Its mostly convenience and to avoid preloading the images. Since no additional requests have to be sent to the server to display the image, the image will be displayed as soon as you set this value to the src attribute.
In terms of amount of data downloaded, this technique avoids the extra overhead of additional requests but the total sizes downloaded could be a bit larger since the entire image data is encoded in base64. In applications where you might have lots of such images preloading could be a better.
A request to that image file takes longer than showing the image from the binary. So your page has saved some requests :)
I want to calculate how much bandwidth a some Javascript code will consume, based on what I'm seeing in Chrome's developer tools.
The script is initiated through a one-liner Javascript tag, referencing the external JS file.
In the looking at the Initiator and Size Columns:
Initiator Size
-------------------------------------------
Default.aspx 4.39kb
Parser 10.54kb
That Javascript file exists on my server, so I want to calculate how much bandwidth each call will consume from my server connection (not where Default.aspx resides).
So my server serves up the .JS at 4.39kb - or is that the bandwidth consumption for the request, and the response is 10.54kb?
What does the parser portion refer to, and is it safe to say that the total bandwidth usage to serve up a response for this request 15.47kb from my server?
Thanks.
In the initiator column first line represents file and line number where this request was initiated.
Second line represents the type of the initiator.
In your case this request was initiated by HTML parser while parsing Default.aspx (your main document I guess).
As you can see from column header, in the size column first line represents size - meaning transfer size, and the second line represents Content size - meaning actual size of the resource data. Resources are often served compressed and this is probably the case here:
response size was 4.39kb and script size was 10.54kb after decompression.
There is no any information about request size, but it is usually quite small unless you have uploaded some data by your request.
Please note that in the bottom of network panel there is a line showing total requests count and total transfer size which is probably what you need.
You're reading the columns wrong. The two values for the initiator you're seeing are completely unrelated to the two values you're seeing for size for each resource.
The "Parser" value for the initiator means the parser came across a <script> tag and loaded it (or an <img> tag, whatever). A "script" value means a piece of JavaScript demanded the loading of the resource (e.g. setting the src of an <img/> or via AJAX).
The top value in the "Size" columns is what Chrome calls "Size" and the second (smaller/ gray) value is the "Content". Quite what these mean, I'm trying to work out.
It's true that the total bandwidth usage will be the sum of some values from the Size column... but I'm not sure whether it's the top or bottom value. It's also completely unrelated to the "Initiator".