Miranda N
Miranda N

Reputation: 75

why does my jQuery .load() fail randomly?

I have a couple of scripts to 1) load a Markdown file into a div then 2) convert it to HTML and insert it into another div. Using Visual Studio Code to live-preview the page, the converted text sometimes appears, sometimes doesn't, upon saving the files or reloading the page. It fails to appear always when I manually open the page from the browser (Chrome) or drag it into it. The conversion itself works, successfully replacing the markups with HTML tags. The problem might be the sequence in which the scripts/lines are run. But the failure seems random: it can occur however quickly or slowly I reload the page.

Here's the page code

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>

<div id="input" style="display: none;"></div>
<script>
  $("#input").load("convertme.md");
</script>

<div id="output"></div>
<script src="converter.js"></script>

</body>

and here's the external conversion script (without the .replace lines, omitted just for this post)

$(document).ready(function() {

  input = document.getElementById('input');
  output = document.getElementById('output');

  function convert(md){
    ... // this part has the lines that replace the original markups with HTML tags
    return md;
  };

  output.innerHTML = convert(input.innerText);
});

Any suggestion?

Upvotes: 0

Views: 123

Answers (1)

Thallius
Thallius

Reputation: 2619

.load() is a asynchronous function. So it might be that your convert is done before the load is finished. You need to call your convert function in the finish callback of your load function

<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
   <script src="converter.js"></script>
</head>

<body>
    <div id="input" style="display: none;"></div>       
    <div id="output"></div>
</body>

$(document).ready(function() {

  let input = document.getElementById('input');
  let output = document.getElementById('output');

  function convert(md){
        ... // this part has the lines that replace the original markups with HTML tags
    return md;
  };

  $("#input").load("convertme.md", function()
  {
       output.innerHTML = convert(input.innerText);    
  });
});

Upvotes: 1

Related Questions