Bookmarklet等到Javascript加载完毕 [英] Bookmarklet wait until Javascript is loaded

查看:163
本文介绍了Bookmarklet等到Javascript加载完毕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载jQuery和其他一些js库的bookmarklet。

I've got a bookmarklet which loads jQuery and some other js libraries.

我如何:


  • 等到我正在使用的javascript库可用/已加载。如果我在加载之前尝试使用脚本,比如在加载之前使用带有jQuery的$ function,则抛出一个未定义的异常。

  • 确保我加载的书签不会被缓存(不使用服务器头,或者显然,这是一个javascript文件:一个元标记

  • Wait until the javascript library I'm using is available/loaded. If I try to use the script before it has finished loading, like using the $ function with jQuery before it's loaded, an undefined exception is thrown.
  • Insure that the bookmarklet I load won't be cached (without using a server header, or obviously, being that this is a javascript file: a metatag)

是否有人知道动态添加的javascript onload是否可以在IE中运行? (与此发布相矛盾)

Is anyone aware if onload for dynamically added javascript works in IE? (to contradict this post)

这些问题最简单的解决方案,最干净的解决方案是什么?

What's the simplest solution, cleanest resolution to these issues?

推荐答案

这取决于你实际加载jQuery的方式。如果要向页面添加脚本元素,则可以使用jQuery用于动态加载脚本的相同技术。

It depends on how you are actually loading jQuery. If you are appending a script element to the page, you can use the same technique that jQuery uses to dynamically load a script.

编辑:我完成了我的作业,实际上从jQuery代码中提取了一个loadScript函数,以便在你的书签中使用。它实际上可能对许多人(包括我)有用。

EDIT: I did my homework and actually extracted a loadScript function from the jQuery code to use in your bookmarklet. It might actually be useful to many (including me).

function loadScript(url, callback)
{
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");
    script.src = url;

    // Attach handlers for all browsers
    var done = false;
    script.onload = script.onreadystatechange = function()
    {
        if( !done && ( !this.readyState 
                    || this.readyState == "loaded" 
                    || this.readyState == "complete") )
        {
            done = true;

            // Continue your code
            callback();

            // Handle memory leak in IE
            script.onload = script.onreadystatechange = null;
            head.removeChild( script );
        }
    };

    head.appendChild(script);
}


// Usage: 
// This code loads jQuery and executes some code when jQuery is loaded
loadScript("https://code.jquery.com/jquery-latest.js", function()
{
    $('my_element').hide();
});

这篇关于Bookmarklet等到Javascript加载完毕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆