【问题标题】:How can I Load external Css files Using jquery/AJAX?如何使用 jquery/AJAX 加载外部 Css 文件?
【发布时间】:2016-12-30 05:56:51
【问题描述】:

我在 10 秒后发送 AJAX 请求以从 Nodejs 服务器获取数据,但我一直收到解释为样式表并转换为 mime 类型 html/css 的资源。服务器正在返回 text/html 。代码工作正常,但外部 css dosnt 工作。以下代码在功能方面对我来说很好,但我想加载外部 css 文件

我的代码在这里

$(document).ready(function() {
    timer = window.setTimeout(function() {
        $.ajax({
            url: '/jrt/?Id=$data.jet.id',
            method: "GET",
            cache: false,
            success: function(data) {
                //$("#gt").append(data);
                $('#gt').html(data);
                if (state == 'jr' || state == 'jt')
                {
                    window.clearTimeout(timer);
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert('error ' + textStatus + " " + errorThrown);
            }
        })
    }, 10000);
});

【问题讨论】:

标签: javascript jquery html css ajax


【解决方案1】:

基于this 的回答。它似乎只是通过javascript。

这段代码创建了一个 id,用 if 语句 link.id 检查它是否已经存在。然后它会创建一个<link></link>,然后添加所有属性。

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.createElement('link');
    link.id   = cssId;
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = 'http://website.com/css/stylesheet.css';
    link.media = 'all';
    head.appendChild(link);
}

未经测试,但也许这会起作用:

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
    var $head  = $('head');
    var link  = document.createElement('link');
    link.attr({
        id:cssId, 
        rel:'stylesheet',
        type:'text/css',
        href:'http://website.com/css/stylesheet.css', 
        media:'all'
    });
    $head.append(link);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多