获取当前正在执行的js文件的URL时,动态加载 [英] Get the url of currently executing js file when dynamically loaded

查看:230
本文介绍了获取当前正在执行的js文件的URL时,动态加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想动态加载的脚本,并找出在其中加载该脚本的URL路径。因此,一些家伙给了我一个pretty的真棒解决这个问题,如果是静态加载脚本(<一href="http://stackoverflow.com/questions/2255689/how-to-get-the-file-path-of-the-currenctly-executing-javascript-$c$c">http://stackoverflow.com/questions/2255689/how-to-get-the-file-path-of-the-currenctly-executing-javascript-$c$c )。但我需要一个动态加载的解决方案。例如:

  $(函数()
{$ .getScript(brilliant.js功能(数据,textStatus)
    {   // 没做什么
    });
});
 

,其中brilliant.js有:

  VAR脚本= document.getElementsByTagName(脚本);
变种SRC =脚本[scripts.length-1]的.src;
警报(这是:+ SRC);
 

在理想情况下,这应该是打印出brilliant.js或与郎;主机+ basepath&响; /brilliant.js

目前brilliant.js作品中静态包含的脚本,而不是脚本动态包含(像$ .getScript)。任何人有什么想法?有没有什么地方的,它存储所有已装?脚本的DOM

编辑:安德拉什给了pretty的很好的解决方案,但它可能只对jQuery的。因为这可能是最流行的库,肯定什么,我打算使用。这大概可以同时扩展到其他库。这是我的简化版本:

  VAR scriptUri;
curScriptUrl(函数(X)
{scriptUri = X;
    警报(scriptUri);
});

功能curScriptUrl(回调)
{VAR脚本= document.getElementsByTagName(脚本);
    VAR scriptURI =脚本[scripts.length-1]的.src;

    如果(scriptURI!=)//静态包含
    {回调(scriptURI);
    }否则,如果($!= undefined)的// jQuery的AJAX
    {$(文件).ajaxSuccess(函数(即XHR,S)
        {回调(s.url);
        });
    }
}
 

解决方案

在你的脚本被加载使用jQuery(我猜其他框架也一样),你的脚本将变得一个脚本,原在区分HTML文档。

的jQuery发出请求,伸出你的脚本,并把后面的回复为:其中的文本子;脚本&GT;节点。您的浏览器没有办法知道它源于,无论是之前插入这仅仅是一个脚本节点,据她而言修改等。

可以有解决方法,但是。在jQuery的情况下,你可以连接到AJAX事件和利用的事实,他们是正确的叫你的脚本执行之后。基本上,这会产生在你的榜样brilliant.js:

  VAR处理程序=函数(即XHR,S){
    警报(s.url);
}

$(文件).ajaxSuccess(处理);
 

一个更复杂的之一:

 (功能($,未定义){

    / *让我们试图找出我们是否内联。* /
    VAR脚本= document.getElementsByTagName(脚本);

    如果(脚本[scripts.length  -  1] .src.length === 0){
        //是的,我们都是内联。
        //看看我们是否有jQuery的加载我们AJAX在这里。
        如果($!== undefined)的{
            VAR初始化= FALSE;
            VAR ajaxHandler =功能(即XHR,S){
                如果(!初始化){
                    初始化= TRUE;
                    警报(内联:+ s.url);
                    initmywholejsframework();
                }
            }

            //如果是,我们的处理程序将被调用后立即被载入该文件。
            $(文件).ajaxSuccess(ajaxHandler);

            //确保删除我们的处理如果我们屈服了。
            window.setTimeout(函数(){
                jQuery的(文件).unbind(的ajaxSuccess,ajaxHandler);
                如果(!初始化){
                    handleInlinedNonjQuery();
                }
            },0);

        }
    } 其他 {
        //我们也包括在内。
        警报(包括:+脚本[scripts.length  -  1]的.src);
        initmywholejsframework();
    }

    //处理其他JS框架等在这里,如果你愿意。
    功能handleInlinedNonjQuery(){
        警报(nonJQuery);
        initmywholejsframework();
    }

    //这里初始化您的lib
    功能initmywholejsframework(){
        警报(装);
    }

})(jQuery的);
 

So I'm trying to load a script dynamically and figure out the URL path at which that script was loaded. So some guy gave me a pretty awesome solution to this problem if the scripts are statically loaded ( http://stackoverflow.com/questions/2255689/how-to-get-the-file-path-of-the-currenctly-executing-javascript-code ). But I need a dynamically loaded solution. For example:

$(function()
{   $.getScript("brilliant.js", function(data, textStatus)
    {   // do nothing   
    });
});

where "brilliant.js" has:

var scripts = document.getElementsByTagName("script");
var src = scripts[scripts.length-1].src;
alert("THIS IS: "+src);

Ideally this should either print out "brilliant.js" or "⟨hostname+basepath⟩/brilliant.js"

Currently brilliant.js works for statically included scripts, but not for scripts included dynamically (like with $.getScript). Anyone have any ideas? Is there somewhere in the dom that stores all the scripts that have been loaded?

EDIT: Andras gave a pretty good solution, though it probably only works for jQuery. Since that's probably the most popular library, and definitely what I'm going to be using. It can probably be extended for other libraries as well. Here's my simplified version:

var scriptUri;
curScriptUrl(function(x)
{   scriptUri = x;
    alert(scriptUri);
});

function curScriptUrl(callback)
{   var scripts = document.getElementsByTagName("script");
    var scriptURI = scripts[scripts.length-1].src;  

    if(scriptURI != "")         // static include
    {   callback(scriptURI);
    }else if($ != undefined)    // jQuery ajax
    {   $(document).ajaxSuccess(function(e, xhr, s)
        {   callback(s.url);
        }); 
    }
}

解决方案

When your script gets loaded with jQuery (and I guess other frameworks as well), your script will become indistinguishable from a script that was originally in the HTML document.

jQuery makes a request reaching out for your script and puts back the reply as the text child of a <script> node. Your browser has no way of knowing where it originated from, whether it was modified before inserted, etc. It is just a script node as far as she is concerned.

There can be workarounds, however. In the case of jQuery, you can hook up to the ajax events and exploit the fact that they are called right after your script executes. Basically, this would yield "brilliant.js" in your example:

var handler = function (e, xhr, s) {
    alert(s.url);
}

$(document).ajaxSuccess(handler);

A more elaborate one:

(function ($, undefined) {

    /* Let's try to figure out if we are inlined.*/
    var scripts = document.getElementsByTagName("script");

    if (scripts[scripts.length - 1].src.length === 0) {
        // Yes, we are inlined.
        // See if we have jQuery loading us with AJAX here. 
        if ($ !== undefined) {
            var initialized = false;
            var ajaxHandler = function (e, xhr, s) {
                if (!initialized) {
                    initialized = true;
                    alert("Inlined:" + s.url);
                    initmywholejsframework();
                }
            }

            //If it is, our handler will be called right after this file gets loaded.
            $(document).ajaxSuccess(ajaxHandler);

            //Make sure to remove our handler if we ever yield back.
            window.setTimeout(function () {
                jQuery(document).unbind("ajaxSuccess", ajaxHandler);
                if (!initialized) {
                    handleInlinedNonjQuery();
                }
            }, 0);

        }
    } else {
        //We are included.
        alert("Included:" + scripts[scripts.length - 1].src);
        initmywholejsframework();
    }

    //Handle other JS frameworks etc. here, if you will.
    function handleInlinedNonjQuery() {
        alert("nonJQuery");
        initmywholejsframework();
    }

    //Initialize your lib here
    function initmywholejsframework() {
        alert("loaded");
    }

})(jQuery);

这篇关于获取当前正在执行的js文件的URL时,动态加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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