Dynamic loading of template files into a div not w

2019-08-30 10:03发布

问题:

Im using the following code to load the html file containing my templates into a div dynamically it is working fine in all the browsers except IE8 and lower

JS Function:

function loadHTML(url, callback) {
    $.ajax({
        url: url,
        success: function(res) {
            var div = document.createElement("div");
            div.setAttribute("id", "downloadIFrame");
            document.body.appendChild(div);
            document.getElementById("downloadIFrame").innerHTML = (res);            
            callback();
        }
    });
}

template.html:

<script type="text/html" id="tmpl1">
    <div>sdfsdf</div>
</script>

<script type="text/html" id="tmpl2">
    <div>dddd</div>
</script>

回答1:

Since you're already using jQuery, why not do the following:

function loadHTML(url, callback) {
  $.get(url, function(res){
    $('<div>')
      .attr('id', 'downloadIFrame')
      // I add the element to the DOM **after**
      // setting the html to increase performance.
      // Manipulating elements already in the DOM
      // is computationally expensive
      .html(res)
      .appendTo('body')
    ;//div

    if(callback) callback();
  });
}