Q:

Run google script on dialog open

I am trying to create a script that would get the URL of an image from the active cell, open up a dialog box and display that image. Through lots of googling and trials and errors I have come up with the code below that displays the image in the dialog box when the user clicks "Read Cell B2" button. Please see the spreadsheet in this link.
Question: How to avoid the "Read Cell B2 button" so that the image would automatically be loaded when the dialog box opens? 
IndexQ.html:
<!DOCTYPE html>
<html>
  <head> 
    <base target="_top">
  </head>
  <body>
    <script>
      function onSuccess(B2Value) {
      //document.getElementById('output').innerHTML = B2Value;
      document.getElementById('img2').src = B2Value;
      }
    </script>
<div>
    <input type="button" value="Read Cell B2" 
    onclick="google.script.run.withSuccessHandler(onSuccess).returnCellValue('B2')" />
    <br /> 
      Cell B2 contains value: <div id="output"></div> 
    <br />
    <img id="img2" src="" alt="Second Image" height="300">
    <input type="button" value="Close Sidebar" onclick="google.script.host.close()" /></div>
  </body>
</html>

And Code.gs:
function onOpen() {
 SpreadsheetApp.getUi()
  .createMenu('Sidebar').addItem('OpenDialog', 'openDialog').addItem('OpenSidebar', 'openSidebar').addToUi()
}

function returnCellValue(cell) {
 return SpreadsheetApp.getActiveSheet().getRange(cell).getValue();
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile('IndexQ').setSandboxMode(HtmlService.SandboxMode.IFRAME).setHeight(500);
  SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
}

A:

You can either use templated HTML with a scriptlet:
<img id="img2" src="<?!= returnCellValue('B2') ?>" alt="Second Image" height="300">

Force-printing scriptlets
You'll need to modify the code that opens the dialog:
function openDialog() {
  var html = HtmlService.createTemplateFromFile('IndexQ')
    .evaluate()
    .setSandboxMode(HtmlService.SandboxMode.IFRAME).setHeight(500);

  SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
}

Note the createTemplateFromFile() and evaluate() methods.
or use an onload function that runs when the dialog is opened:
  <script>
    console.log('it ran!');

    window.onload = function() {//Runs after dialog is loaded
      google.script.run.withSuccessHandler(onSuccess).returnCellValue('B2');

    };
  </script>
</html>

