javascript – The performance of the code for calculating the size of the visible part of the screen without refreshing the page

Question:

In the process of layout, I am faced with the need to know the size of the visible part of the screen. To do this, I add the following code:

var html = document.documentElement;
var debugging_block = document.getElementById('debugging');
debugging_info = "Размер видимой области: " + html.clientWidth + "х" + html.clientHeight;
debugging_block.innerHTML = debugging_info;
<div id='debugging'></div>

How can I make this code work without refreshing the page, similar to media query in CSS?

Answer:

wrap the js code in window.onresize = function() {} – but then it only works after the window is changed

Create a separate function with this code.

function Foo()
{
  var html = document.documentElement;
  var debugging_block = document.getElementById('debugging');
  debugging_info = "Размер видимой области: " + html.clientWidth + "х" + html.clientHeight;
  debugging_block.innerHTML = debugging_info;
}

Then use it as an event handler for two events

window.onload = Foo;
window.onresize = Foo;

Then, it will work not only when resizing, but also immediately when loading.

Scroll to Top