Google API Loader setOnLoadCallback() - DOM准备好了吗?

时间:2010-11-06 17:52:07

标签: javascript jquery google-api domready

我正在使用SWFObject和替代内容(没有Flash)我想使用jQuery插件 显然我只想在Flash不可用时加载jQuery和插件脚本。所以谷歌的API Loader看起来很完美。

现在我遇到了setOnLoadCallback()事件的问题。它似乎应该被触发,但也许在DOM准备好之前? 我在SO上发现another question,显示在DOM加载上有第二个未记录的参数。
但我仍然无法访问jQuery!

<script type="text/javascript" src="https://www.google.com/jsapi?key=INSERT-YOUR-KEY"></script>
<script type="text/javascript">
    google.load("swfobject", "2.2");
</script>
<script type="text/javascript">
    swfobject.embedSWF("slideshow.swf", "slideshow", "800", "530", "7","expressInstall.swf", null, null, null, flashNotLoaded);

    function flashNotLoaded(e) {
        if (!e.success) {
            google.load("jquery", "1.4.2");
            google.setOnLoadCallback(jQueryLoaded, true);
        }
    }

    function jQueryLoaded() {
        alert("jquery loaded");
        $("body").css("background-color","ff00ff"); // does not work....
        $(function() {
            $("body").css("background-color","ff0000"); // neither does this...
        });
    }
</script>

编辑:似乎jQuery等图书馆的google.load仅适用于window.load
只有少数谷歌自己的API可以动态加载回调 请参阅:Google Library API - google.load does not load from event?

2 个答案:

答案 0 :(得分:1)

我怀疑在调用jQueryLoaded时DOM实际上还没有准备好。您应该确保从使用swfobject.embedSWF注册的回调中调用swfobject.addDomLoadEvent

答案 1 :(得分:0)

@MPD注意到DOM没有准备好,所以我使用swfobject.addDomLoadEvent进行了回调 在这里使用google.load("jquery", "1.4.3"); jQuery似乎没有加载?

<script type="text/javascript" src="https://www.google.com/jsapi?key=INSERT-YOUR-KEY"></script>
<script type="text/javascript">
    google.load("swfobject", "2.2");
    google.setOnLoadCallback(swfobjLoaded);

    function swfobjLoaded() {
        swfobject.embedSWF("slideshow.swf", "slideshow", "800", "530", "7","expressInstall.swf", null, null, null, swfobjSuccess);
        swfobject.addDomLoadEvent(swfobjDOMReady);
    }

    var isSWFEmbedded = true;
    function swfobjSuccess(e) {
        if (!e.success) {
            isSWFEmbedded = false;
        }
    }

    function swfobjDOMReady() {
        if (!isSWFEmbedded) {
            alert("dom is ready, Flash is not embedded, now load jquery"); // everything works fine untill here
            google.load("jquery", "1.4.3"); // does not load, page goes blank??
            google.setOnLoadCallback(jqueryLoaded);
        }
    }

    function jqueryLoaded() {
        $("body").css("background-color","ff0000");
    }
</script>