Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax not adding <link> in <head> tags in IE

Tags:

jquery

I am loading a page via AJAX and putting it in a DIV. Including HTML tags and all. No browser seems to be worried about that, except for the fact that the <head> elements never load in IE, but do so in FF.

Is it possible to let the elements in <head> to load as well, or do I have to put them in the body?

This includes <title> and <link>. But the <style> element works fine. So I can't load my external stylesheets with my Ajax. Is there a way, or do I have to put it in the body?

Thanks in advance.

Code example:

// page to load
<html>
<head>
    <link href="{$cssLink}" type="text/css" rel="stylesheet"> // doesn't load
    <style type="text/css">
    /* CSS bla does work*/
    </style>
</head>
<body>
    <div id="testPage_content" class="content">
</div>
</body>
</html>

And the ajax call I am making, if you would need that in your answer.

// ask for the page
$.ajax(
{
    url: "Scripts/loader.php",  
    type: "GET",        
    data: data, // created above this call
    cache: false,
    success: function (html) 
    {               
        //add the content retrieved from ajax and put it in the #content div
        $('#content').html(html);       

        // only use fading if opacity is supported          
        if($.support.opacity)
        {
            $('#loading').hide();
            $('#content').fadeIn();
        }
    }
});
like image 376
Marnix Avatar asked Oct 24 '22 21:10

Marnix


1 Answers

You really should use an <iframe> element to load a "complete" website (means with <html>, <body> and <head> tags. It's 100% invalid markup otherwise.

I meantioned it would be nasty work to strip, but.. woh maybe not that nasty:

success: function (html) 
{               
    //add the content retrieved from ajax and put it in the #content div
    var stripped = $(html),
        head     = document.getElementsByTagName('head')[0] || document.documentElement;

    stripped.find('head').contents().each(function(index, node) {
        if(node.nodeType !== 3) {
           node.setAttribute('data-insertID', 'foobar');
           head.appendChild(node, head.firstChild);
        }
    });

    $('#content').html(stripped.find('body').contents());       

    // only use fading if opacity is supported          
    if($.support.opacity)
    {
        $('#loading').hide();
        $('#content').fadeIn();
    }
}

Delete with:

$('head').find('[data-insertID]').remove();

This would grab all nodes from the head section of your received site and put it into your actuall website. After that it gets all nodes from the <body> tag and puts those into your div.. should work, let me know :)

like image 119
jAndy Avatar answered Nov 09 '22 07:11

jAndy