没有带嵌套脚本的src的Javascript iframe

时间:2013-08-01 00:39:44

标签: javascript

是否可以在iframe插入dom之前在其head元素中创建一个iframe,并在脚本onload="alert(1)"准备就绪时触发?

示例1,使用嵌套脚本:

var iframe  = jQuery("<iframe></iframe>");
var scripts =  '' +
            '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"          onload="alert(1);"><\/script>' +
            '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js" onload="alert(2);"><\/script>';

iframe.html(scripts);

jQuery("body").append(iframe);

示例二,更大:

function loadScript(path, callback, appendTo) {
        var element = document.createElement('script');
        element.setAttribute ("type", 'text/javascript');
        element.setAttribute ("src", path);

        return loadElement(element, callback, appendTo);
}

function loadElement(element, callback, appendTo) {
        element.loaded = false;

        if (element.readyState){  // IE
                element.onreadystatechange = function(){
                        if (element.readyState == "loaded" || element.readyState == "complete"){
                                element.onreadystatechange = null;

                                loadElementOnLoad(element, callback);
                        }
                };
        } else {                 // Others
                element.onload = function() {
                        loadElementOnLoad(element, callback);
                };
        }

        (appendTo).appendChild(element);

        return element;
}

function loadElementOnLoad(element, callback) {
        if (element.loaded != true) {
                element.loaded = true;
                if ( callback ) callback(element);
        }
}


function loadScriptNew1(src, callback, appendTo) {
        loadScript(src, callback, appendTo)
}

var iframe  = jQuery("<iframe></iframe>");

loadScriptNew1("http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js", function() {
        alert(11)
}, iframe.get(0) )


loadScriptNew1("http://ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js", function() {
        alert(22)
}, iframe.get(0) )

jQuery("body").append(iframe)

这些方法都不会触发onload函数'alert;

这可能吗?在两种情况下都会加载脚本,因为它们的窗口对象已设置,但没有回调。

1 个答案:

答案 0 :(得分:0)

试试这个:

<html>
<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script type="text/javascript">
  function insertIframe() {
  var iframe = $('<iframe></iframe>').appendTo('body')[0];

  // switch to straight JS
  var script = iframe.contentWindow.document.createElement("script");
  script.type = "text/javascript";
  script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
  script.onload = function() { alert(1); };
  iframe.contentWindow.document.body.appendChild(script);

}

</script>
</head>
<body onload="insertIframe()">
</body>