I am using bootstrap 3 modal dialogs with remote sources. My Problem is that I use external JavaScript and script blocks in those remote sources. When I open and Close a modal Dialog and then reopen it, the JavaScript is loaded twice.

How can I suppress from loading the same JavaScript file again when reopening the modal Dialog? Or how can I destroy the loaded JavaScript when closing the Dialog?

JavaScript:

<!-- language: lang-js -->
$(function() {
    $('[data-load-remote]').on('click',function(e) {
        e.preventDefault();
        var $this = $(this);
        var remote = $this.data('load-remote');
        if(remote) {
            $($this.data('remote-target')).load(remote);
        }
    });
});

HTML:

<!-- language: lang-html -->
<a href="#myModal" role="button" class="btn" data-toggle="modal" 
   data-load-remote="http://localhost/dashboard/myprices"
   data-remote-target="#myModal .modal-body">My Salon (Preview)</a>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"
                aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

You can use another data- attribute to check whether it's loaded or not:

Add isloaded="false" to your anchor tag like so:

<!-- language: lang-html -->
<a data-isloaded="false" href="#myModal" role="button" class="btn" data-toggle="modal" 
   data-load-remote="http://localhost/dashboard/myprices" 
   data-remote-target="#myModal .modal-body">My Salon (Preview)</a>

Then you can check if it's been loaded using $this.data('isloaded'). If it has, get out of there, if not, load it and set the flag like so: $this.data('isloaded', true).

Here's some JavaScript

<!-- language: lang-js --> <pre><code>$(function() { $('[data-load-remote]').on('click',function(e) { e.preventDefault(); var $this = $(this); var remote = $this.data('load-remote'); <b>if (!$this.data('isloaded')) {</b> if(remote) { $($this.data('remote-target')).load(remote); <b>$this.data('isloaded', true)</b> } } }); }); </code></pre>

jsFiddle


UPDATE for clarification based on comment

From the HTML5 spec on custom data attributes:

Every HTML element may have any number of custom data attributes specified, with any value.

i.e. There is no predefined data-isloaded, the same as there is no predefined data-load-remote. You could just as easily call it data-kylePromisesTheValueIsLoaded. As long as that's the string you pass to the .data() method, then it will read / write the value for that attribute.