Appending Link To Head Of Iframe

為{幸葍}努か 提交于 2019-12-23 01:34:11

问题


I want to append element To head of an Iframe (fancybox)

there is a strange problem : when I use Firefox to Breakpoint on line of code that append element to Head it works correctly but when I run site normally without firebug it does not work;

I am using fancybox 1.3.4 and the code run in onComplete event

var cssLink = document.createElement("link") 
cssLink.href = "/themes/furniture/css/test.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 


var f123= document.getElementById('fancybox-frame');

var d123= f123.contentDocument || f123.contentWindow.document;

d123.head.appendChild(cssLink); 

UPDATE

I also try this code

var $head = $("#fancybox-frame").contents().find("head");                
$head.append($("<link/>", 
{ rel: "stylesheet", href: "/themes/furniture/css/test.css", type: "text/css" } )); 

but it does not work either

Tnx


回答1:


Well, it seems to be a racing condition indeed (as pointed out by olsn in his comment) between loading the iframe and finding elements inside of it, which fails if the second occurs first ;)

As a workaround, you could use the .load() method to wait for the iframe to be completely loaded before trying to append the stylesheet to the <head> section.

This code should do the trick :

$(document).ready(function () {
    $(".fancybox").fancybox({
        "type": "iframe",
        "onComplete": function () {
            var $style = '<link rel="stylesheet" href="/themes/furniture/css/test.css" type="text/css" />';
            $("#fancybox-frame").load(function () {
                $(this).contents().find("head").append($style);
            });
        }
    });
});

Note : this is for fancybox v1.3.4. Fortunately v2.x includes more flexible public methods than v1.3.4 to circumvent this issue, like afterLoad and beforeShow

Also notice that setTimeout() will work too, but it renders oddly.



来源:https://stackoverflow.com/questions/16241296/appending-link-to-head-of-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!