Javascript showing HTML before CSS and JS load

I am using Pjax in my project, it is working very perfectly, but I have an issue that it is loading HTML first. I want it will load CSS and JS after it will show HTML.
how did I achieve the goal, even though I am using DOMContentLoaded, I also used the window and load function but it also not worked.
Is there any method that we can load the CSS and JS file first and then HTML to prevent bad UI for few times until the page is not fully loaded?

<script src="../../../node_modules/pjax/pjax.min.js"></script>
<script>
  /* global Pjax */
  var pjax;
  var initButtons = function () {
    var buttons = document.querySelectorAll(".js-Pjax");

    if (!buttons) {
      return;
    }

    // jshint -W083
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].addEventListener("click", function (e) {
        var el = e.currentTarget;

        pjax.loadUrl(el.getAttribute("href"));
      });
    }
  };

  document.addEventListener("pjax:send", function () {
    //console.log("Event: pjax:send", arguments);
  });

  document.addEventListener("pjax:complete", function () {
    //console.log("Event: pjax:complete", arguments);
  });

  document.addEventListener("pjax:error", function () {
    //console.log("Event: pjax:error", arguments);
  });

  document.addEventListener("pjax:success", function () {
    //console.log("Event: pjax:success", arguments);

    // Init page content
    initButtons();
  });

  document.addEventListener("DOMContentLoaded", function () {
    // Init Pjax instance
    pjax = new Pjax({
      elements: [".js-Pjax"],
      selectors: ["main", "title"],
      cacheBust: false
    });
    // console.log("Pjax initialized.", pjax);

    // Init page content
    initButtons();
  });
</script>

So it’s working perfectly, but it’s got an issue. Mkay.

Well, your script tells it to wait until the HTML is loaded:
document.addEventListener("DOMContentLoaded", function () {
But… it relies on an element to exist:

so the element must exist before the pjax can run on it. Which means… the HTML has to load.

yes, it exist already

I… am confused then.

You want the javascript to run before the HTML, but acknowledge that the HTML must already exist before the javascript can run.

Unless you’ve got a time machine somewhere, we’re stuck in a linear progression, in which case these two things cannot be.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.