小书签等待 Javascript 加载

发布于 2024-07-17 23:10:43 字数 407 浏览 5 评论 0原文

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

我该如何:

  • 等到我正在使用的 javascript 库可用/加载。 如果我尝试在脚本完成加载之前使用该脚本,例如在加载之前将 $ 函数与 jQuery 一起使用,则会引发未定义的异常。
  • 确保我加载的小书签不会被缓存(不使用服务器标头,或者显然,这是一个 javascript 文件:元标记

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

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

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

How do I:

  • 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)

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

下壹個目標 2024-07-24 23:10:43

这取决于您实际加载 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();
});

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.

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();
});
南街女流氓 2024-07-24 23:10:43

回答你的第一个问题:Javascript 是按顺序解释的,因此在加载库之前,任何后续的小书签代码都不会执行(假设库被成功解释 - 没有语法错误)。

为了防止文件被缓存,您可以附加一个无意义的查询字符串...

url = 'jquery.js?x=' + new Date().getTime();

To answer your first question: Javascript is interpreted sequentially, so any following bookmarklet code will not execute until the library is loaded (assuming the library was interpreted successfully - no syntax errors).

To prevent the files from being cached, you can append a meaningless query string...

url = 'jquery.js?x=' + new Date().getTime();
天气好吗我好吗 2024-07-24 23:10:43

我注意到,在 Chrome 中,使用 @Vincent Robert 的技术时,加载脚本的顺序是不确定的。 在这种情况下,进行一些修改会有所帮助:


(function() {
    var callback = function() {
        // Do you work
    };
        // check for our library existence
    if (typeof (MyLib) == 'undefined') {
        var sources = [
                'http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js',
            'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
            'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js',
            'http://myhost.com/javascripts/mylib.min.js'];

        var loadNextScript = function() {
            if (sources.length > 0) {
                var script = document.createElement('script');
                script.src = sources.shift();
                document.body.appendChild(script);

                var done = false;
                script.onload = script.onreadystatechange = function() {
                    if (!done
                            && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
                        done = true;

                        // Handle memory leak in IE
                        script.onload = script.onreadystatechange = null;

                        loadNextScript();
                    }
                }
            } else {
                callback();
            }
        }
        loadNextScript();

    } else {
        callback();
    }
})();

I've paid an attention that in Chrome the order of scripts that are loaded is undetermined, when using @Vincent Robert's technique. In this case a little modification helps:


(function() {
    var callback = function() {
        // Do you work
    };
        // check for our library existence
    if (typeof (MyLib) == 'undefined') {
        var sources = [
                'http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js',
            'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
            'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js',
            'http://myhost.com/javascripts/mylib.min.js'];

        var loadNextScript = function() {
            if (sources.length > 0) {
                var script = document.createElement('script');
                script.src = sources.shift();
                document.body.appendChild(script);

                var done = false;
                script.onload = script.onreadystatechange = function() {
                    if (!done
                            && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
                        done = true;

                        // Handle memory leak in IE
                        script.onload = script.onreadystatechange = null;

                        loadNextScript();
                    }
                }
            } else {
                callback();
            }
        }
        loadNextScript();

    } else {
        callback();
    }
})();
熟人话多 2024-07-24 23:10:43

我对这个有了一些了解,但并不完全。 如果有一个独立的小书签示例来演示如何避免缓存,那就太好了。

I got a little closer with this, but not completely. It would be nice to have a discrete, example of a bookmarklet that demonstrated how to avoided caching.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文