I'm adding a module main.js
to my page with as GET-parameter a random number for it to not be cached on mobile where Ctrl+F5 is more complicated when I'm developping.
<script type="module" src="main.js?t=12341234"></script>
Now in this file I have a variable userIsTyping
and an event listener that calls makeAjaxCall
from ajax.js
on input.
import {makeAjaxCall} from "./ajax.js";
export let userIsTyping = false;
// A function has to be created to modify the value from another module https://stackoverflow.com/a/53723394/9013718
export function changeUserIsTyping(value) {
userIsTyping = value;
}
let textarea = document.querySelector('textarea');
let textareaInputPauseTimeoutId;
textarea.addEventListener('input', function () {
// Set var to true as soon as there is a user input
userIsTyping = true;
clearTimeout(textareaInputPauseTimeoutId);
textareaInputPauseTimeoutId = setTimeout(function () {
// Runs 1 second after the last change
makeAjaxCall.call(textarea);
}, 1000);
});
The second module is making the ajax call and the key here is that between the time where the ajax request is started and its response callback, I need to be able to know if userIsTyping
became true
in the meantime.
import {changeUserIsTyping, userIsTyping} from "./main.js";
export function makeAjaxCall() {
changeUserIsTyping(false);
// Make ajax call
let xHttp = new XMLHttpRequest();
xHttp.onreadystatechange = function () {
if (xHttp.readyState === XMLHttpRequest.DONE) {
if (userIsTyping === false) {
// If user typed something between the beginning of the request and now it wouldn't reach here.
} else {
// User typed something in the meantime
}
}
};
xHttp.open('PUT', 'notes/' + this.dataset.noteId, true);
xHttp.setRequestHeader("Content-type", "application/json");
xHttp.send(JSON.stringify({[this.name]: this.value}));
}
This does kind of work but the ajax call is always called twice. I found that the reason could be that the browser loads main.js?t=12341234
that has an event listener on input that calls the makeAjaxCall
and there is also a main.js
(which is the same file but without the GET parameter.
Is there a way to make the browser know that they have identical contents and should not be fully loaded and executed both?
A quick fix would be to put the input event listener into the ajax.js
so that it doesn't have to import main.js
but there are other occurences where I seem to be blocked between importing modules and wanting to add a GET param so that there is no cache on mobile.
But I showed the full context of what I'm trying to do in case anyone has a better idea to do this, I'd love suggestions.