To control my DIY smart thermostat, I’ve created a webpage where some content like the current temperature needs to be refreshed.

I’ve done that successfully by using the following jquery code.

<div id="refresh">

	Content to refresh every second

</div>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    $(document).ready(function() {
                setInterval(function() {
                    $('#refresh').load('./ #refresh');
                }, 1000);
            });
</script>

However, I was not happy that I needed to load a complete jquery-library, just to refresh a part of my page. So, I’ve tried to do the same with plain vanilla javascript.

<div id="refresh">

	Content to refresh every second

</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        setInterval(function() {
            var url = window.location.href;  // get current url
            var id = "#refresh";
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function xhrStateChange() {
                if (xhr.readyState === 4) {                       // 4 	DONE 	The operation is complete.
                    try {
                        document.querySelector(id).innerHTML = xhr.responseXML.querySelector(id).innerHTML;
                    } catch (e) {
                        document.querySelector(id).innerHTML = "<p>No network connection</p>";
                    }
                }
            };

            xhr.open('GET', url);
            xhr.responseType = 'document';
            xhr.send();

        }, 1000);
    });
</script>

My javascript knowledge is limited, but this seems to work just like I wanted :)