0

是否可以在将 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;

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

4

1 回答 1

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>
于 2013-08-01T01:51:07.447 回答