HTML页面引入外部的HTML方法

引入外部文件的四种方法

a、iframe标签

b、ajax引入代码片段

c、link import的方法导入

d、requirejs

iframe

如果是一个完整的外部页面(有完整的html,head,body),可以考虑用iframe。

<iframe src="test.html"></iframe>

ajax

如果仅仅是一个代码片段,也可以用ajax

案例1

$.get('test.html',function(html){
    //
});
$.when(
    $.get('test1.html'),
    $.get('test2.html'),
).then(function(html1,html2){
    console.log(html1[0]);
    console.log(html2[0]);
});

案例2

$(function () {
    $.get("header.html",function (data) {
        $("#header").html(data);
    });
    $.get("footer.html",function (data) {
        $("#footer").html(data);
    });
});

link import的方法导入

<link rel="import" href="test.html">

if (typeof document.querySelector("link[rel = 'import']").import == 'object') {
    var html = document.querySelector("link[rel = 'import']").import.head.innerHTML;
} else {
    $.get('test.html', function(html) {
    });
}

requirejs

最后,也可以使用requirejs…(比ajax方便)

猜你喜欢

转载自blog.csdn.net/qq1092881420/article/details/128753387