Bookmarklet等到Javascript加载完毕

cgp*_*cgp 20 javascript jquery bookmarklet

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

我如何能:

  • 等到我正在使用的javascript库可用/加载.如果我在加载完成之前尝试使用脚本,比如在加载之前使用带有jQuery的$ function,则抛出一个未定义的异常.
  • 确保我加载的书签不会被缓存(不使用服务器头,或者很明显,这是一个javascript文件:metatag)

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

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

Vin*_*ert 24

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

编辑:我做了我的功课,实际上从jQuery代码中提取了一个loadScript函数,用于你的书签.它实际上可能对许多人(包括我)有用.

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();
});
Run Code Online (Sandbox Code Playgroud)

  • 艺术品:) (2认同)