jquery dynamically loads HTML files web page content and dynamically introduces css files and dynamically introduces js files

(1) Only dynamically introduce html content (using url parameters): syntax jquery object.load(url);

Example:

//头部是一个包含html内容的文件
$('header').load('头部.html .container');

Header.html ~ (that is, the html code written with the content you need)

<div class="container">
	<h1>我是头部</h1>
</div>

(2) Dynamically introduce html content and its corresponding css style file: syntax jquery object.load(url, function(){ //Introduce css file in callback function});

Example: ~ The head.css file is a css file that modifies the styles in the head.html

$('header').load('头部.html .container',function(){
    
        
    let link = document.createElement('link');
        $(link).attr({
    
    
          rel:'stylesheet',
          type:'text/css',
          href:'./css/头部.css'
      });
    $('head').append(link);
});

By encapsulating the dynamic introduction of css into a method, you can rewrite the code:

//封装js动态加载css文件
function addCss(href){
    
    
    //判断是否是同文件
    let links = $("link");
    let isHave = false;
    links.each(function (index, element) {
    
    
        if($(element).attr('href') === href) {
    
    
            isHave = true;
        }
    });
    if (isHave) return;
    let link = document.createElement('link');
    $(link).attr({
    
    
        rel:'stylesheet',
        type:'text/css',
        href
    });
    $('head').append(link);
}


//头部:动态加载html页面,且通过function动态引入其对应的css样式
$('header').load('头部.html .container',addCss('./css/头部.css'));
//或者:
$('header').load('头部.html .container',function () {
    
    
    addCss('./css/头部.css');
});

(3) Dynamically introduce html content, and at the same time introduce its corresponding css style files and js files: syntax jquery object.load(url, function(){ //Introduce css files in the callback function, import function of js files});

$('header').load('头部.html .container', function () {
    
    
     addCss('./css/头部.css');
     //使用jquery的函数getScript(参数是 js文件的路径),动态引入js文件
     $.getScript('js/头部.js',function () {
    
    
        //这里可以写在引入头部.js 文件,还动态生成了什么内容
     });
});

Guess you like

Origin blog.csdn.net/lojloj/article/details/124670165