简体   繁体   中英

How can I Load external Css files Using jquery/AJAX?

I am sending AJAX request after 10 seconds to get the data from Nodejs Server but i keep receiving that resources interpreted as Style sheet and converted to mime-type html/css . Server is returning text/html . code works fine but external css dosnt work . the following code works fine for me functionality wise but i want to load external css files

My code here

$(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);
});

Based off this answer. It seems to just by javascript.

This code creates an id that checks if it already exists with the if statement the link.id . It then creates a <link></link> , then adds all the attributes.

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);
}

Untested, but maybe this would work:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM