简体   繁体   中英

Javascript İf Promise Loaded Onclick Then İf Again Onclick Dont Load Again?

var sarki = document.getElementsByClassName("sarki")[0];
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];

sarki.onclick = function () {
  document.getElementsByClassName("siyah")[0].innerHTML = "<div class='loader'></div>";
Promise.all([
  fetch('blabla.txt').then(x => x.text())
]).then(([sarki]) => {
  document.getElementsByClassName("siyah")[0].innerHTML = sarki;
}),modal.style.display = "block",document.title="blabla";
}

span.onclick = function() {
  modal.style.display = "none",document.title="blabla";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none",document.title="blabla";
  }
}

As you can see if button clicked promise will get txt file but again as you can see i open modal and you can close that modal but if you again click that button(without refresh page) that txt file will loaded again... İ just want to check if txt file loaded then dont load again because i make song list but if that loaded again playing song is stopping...

How can i do if file loaded dont load it again with javascript(without library) ?

You need to track whether or not the text file has yet been loaded. You also don't need Promise().all() , since you're dealing with a single factor (the file), not multiple.

let file; //<-- file loaded tracker
sarki.onclick = function () {
    let prom = new Promise(res => {
        !file ?
            fetch('blabla.txt').then(x => res(file = x.text())) :
            res(file);
    });
    prom.then(file => {
        document.getElementsByClassName("siyah")[0].innerHTML = file;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM