最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

external - In Javascript, is it possible to pass a variable into <script> "src" parameter? - Sta

programmeradmin1浏览0评论

Is it possible in Javascript to pass a variable through the src parameter? ie.

<script type="text/javascript" src=".js?handle=aplusk" />`

I'd like twitter.js to look and see if a "handle" was passed before doing what I need it to do and returning its response back to the originating page calling twitter.js.

I had originally created a function in twitter.js that did the following:

function getHandle() {
  var vars = [], hash, username;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

  for(var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    if (hash[0] == 'handle') 
     username = hash[1];
  }

  return username;
}

The problem, and it makes sense, is that window.location.href is not going to work on a file that I'm calling from <script src="" />

Thanks!

Is it possible in Javascript to pass a variable through the src parameter? ie.

<script type="text/javascript" src="http://domain.com/twitter.js?handle=aplusk" />`

I'd like twitter.js to look and see if a "handle" was passed before doing what I need it to do and returning its response back to the originating page calling twitter.js.

I had originally created a function in twitter.js that did the following:

function getHandle() {
  var vars = [], hash, username;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

  for(var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    if (hash[0] == 'handle') 
     username = hash[1];
  }

  return username;
}

The problem, and it makes sense, is that window.location.href is not going to work on a file that I'm calling from <script src="" />

Thanks!

Share Improve this question asked Dec 20, 2010 at 19:52 Mike B.Mike B. 8233 gold badges13 silver badges26 bronze badges 3
  • I'm not sure why you say that window.location.href is not going to work because when the script runs in the page (whether it's external through a src or inline javascript), it will run in the scope of the document which exposes that variable. – sirhc Commented Dec 20, 2010 at 19:59
  • 1 window.location never refers to the url of the script. It refers to the url hosting the script – Ruan Mendes Commented Dec 20, 2010 at 20:19
  • possible duplicate of Pass vars to JavaScript via the SRC attribute – Flimm Commented Jun 30, 2015 at 15:49
Add a comment  | 

4 Answers 4

Reset to default 7

I can see two solutions here.

First: you can process those GET parameters on the server where the twitter.js is hosted, so that it will dynamically change the js file. For example, you file is:

var handle = {{ handle }};

And your server somehow processes the file, replacing that twitter.js template file dependent on what request was sent.

The second option would be to set the global variables on the page where twitter.js is loaded, like this:

<script type="text/javascript">
    window.twitter_js_handle = 'aplusk';
</script>
<script type="text/javascript" src="http://domain.com/twitter.js" />

And in twitter.js:

var handle = window.twitter_js_handle || null;

I use the following pattern to convert query variables from <script src="script.js?foo=bar&baz=zing"></script> to an object containing key:value pairs. Code is placed at the top of script.js:

    var getVars = {};
    
    (function(){
        var scripts, currentScript, queryString;

        scripts = document.getElementsByTagName('script');
        currentScript = scripts[ scripts.length - 1 ];
        queryString = currentScript.getAttribute('src').split("?").pop().split('&');
        for(var i=0;i<queryString.length;i++){
            var keyVal = queryString[i].split('=');
            getVars[ keyVal[0] ] = keyVal[1];
        }
    
    }());
    // console.info( getVars );
    // Object { foo="bar", baz="zing"}

This probably won't work with deferred / asynchronously added script elements, as it relies on immediate code execution.

Sure. But the only way you can access that parameter though is through server-side. So, make twitter.js a PHP page (using mod_rewrite or whatever) that grabs $_GET['handle'] and then serves itself as Content-Type: text/javascript and just dump the contents of the js.

I suggest to use more safe approach - must add an ID:

<script id="myTargetScript" src="http://example.com/file.js?param=value" />

then in your .js file

    function GetParams(target_id)
    {
        var getVars = {};
        if( document.getElementById(target_id) )
        {
            var queryString = document.getElementById(target_id).getAttribute('src').split("?").pop().split("&");
            for(var i=0;i<queryString.length;i++){
                var keyVal = queryString[i].split('=');
                getVars[ keyVal[0] ] = keyVal[1];
            }
        }
        return getVars;
    }
        
        
    // console.log(   GetParams('myTargetScript')   );

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论