JS Tutorial: Passing parameters to JavaScript files

Source: Internet
Author: User
Tags definition eval execution variables script tag variable

First, the use of global variables

This is the simplest way, such as Google Adsense:

<script type= "Text/javascript" >
google_ad_client = ' pub-3741595817388494 ';
</script>
<script type= "Text/javascript" src= "http://pagead2".
Googlesyndication.com/pagead/show_ads.js "></script>

The disadvantage is that global variables are introduced. There are two variations of the way in which files are introduced:

Variant 1: document.write output
<script type= "Text/javascript" >
google_ga_id = ' g6u7un8646xx ';
document.write (unescape ('%3cscript type= "Text/javascript" src= "Http://www.google-analytics.com/ga.js"%3e%3c ")
/script%3e '));
</script>

//Variant 2: Using DOM to manipulate append into head
<script type= "Text/javascript" >
G_BEACON_ATP = ' Category=&userid=&channel=112ad_id= ';
document.getElementsByTagName (' head ') [0].appendchild (document.
createelement (' script ')). src= ' http://taobao.com/atp.js ';
</script>

/Note: The above code is based on the actual application of the virtual model code

Note: Variant 1 is used a lot and is commonly written as follows:

<script type= "Text/javascript" >
//Direct escape:
document.write (' <script type= "Text/javascript" src= " Test.js "></script>");
Or like the Yahoo! Home page:
document.write (' <scr ' + ' IPT type= ' Text/javascript, "src=" test.js "></scr ' + ' ipt> ');
</script>

Second, obtain and parse the src of the script element

As with all variables, we would prefer to pass parameters like this:

<script type= "Text/javascript" src= "Test.js?a=b&c=d" ></script>

The core question is how to obtain the SRC attribute.

The first method is to add an id attribute to the script, get the current script by ID, and then take the parameters out of the SRC. The disadvantage is that the script element has no ID attribute in the HTML 4.01 specification. This shortcoming is also not a shortcoming, after all, the standard is not as good as standard.

The second method is to use JS filename as a hook, JS code passed document.getElementsByTagName('script') , the regular match out of the current JS file. This method is very orthodox, but requires a filename to be unique. The disadvantage is that the code is many, not refined, and has a slight impact on performance.

Method Three, on the basis of method one, simply add another custom attribute data:

<script id= "Testscript" type= "Text/javascript" src= "Test.js" Data= "A=b&c=d" ></script>

In the Test.js file, you get the arguments that are passed in the following line:

var Scriptargs = document.getElementById (' Testscript '). getattribute (' data ');

Method Four is the use of JS sequential execution mechanism (JS file can be loaded synchronously or asynchronously, but the execution, must be in the order of the document flow to execute). When a JS file is executed, it must be the last one in the "Loaded" JS file:

var scripts = document.getelementsbytagname (' script ');
var currentscript = scripts[scripts.length-1];

Method of four more dexterous geniuses.

From the streamlining and performance of the Code, method three > method one > Method four > method two

Summary: If you are very concerned about the standard, recommended method four; If you feel the same as I do not need to fully comply with the standard, recommended method three.

Iii. Inspiration Programme

If you are a loyal fan of John Resig like me, you may remember the "degrading Script Tags", which was very popular last August. John Resig opened an imaginary door for us, and for the purposes of this article, you can use the following "devious" to achieve:

<script type= "Text/javascript" src= "Test.js" >
    TB. Someapp.scriptargs = ' A=b&c=d ';
</script>

In the Test.js file:

TB = {}; TB. Someapp = {};
var scripts = document.getElementsByTagName ("script");
Eval (scripts[scripts.length-1].innerhtml);

This stores the parameters TB.SomeApp.scriptArgs in the variable.

When the parameters are not much, you can even:

<script type= "Text/javascript" src= "Test.js" >a=b&c=d</script>

JS file:

var scripts = document.getElementsByTagName ("script");
var Scriptargs = scripts[scripts.length-1].innerhtml.replace (/[s]/g, "");

Imagination is endless, can also use the onload:

<script type= "Text/javascript" src= test.js "onload=" TB. Somefun (' A=b&c=d ') ></script>

JS file in the definition of a good function can be:

TB = {};
TB. Somefun = function (arg) {//code};

The above code works correctly in non IE browsers. For stupid ie, add a few lines of code:

if (window. ActiveXObject) {
    var scripts = document.getelementsbytagname (' script ');
    Eval (Scripts[scripts.length-1].getattribute (' onload '));

As long as we continue to develop the spirit of excavation, I believe there are more inspiration program-.-

Summarize

Looking at so many solutions above, which is the best solution? My answer is: no best, only the most suitable! because for different applications, and different ideas, the definition of "good" is different.

For example, my current philosophy, I feel that there is no need to fully comply with the standards, and global variables, to avoid is abuse, not without. So I will choose the global variable scheme, the simplest, the best performance.

If it was my colleague pony, who was very compliant, maybe I would choose Method two or method four in the second type of scenario.

Or wait for the small eagle grew up, perhaps directly on the onload program at the same time without giving IE special care, or even directly through some kind of advanced transmission door parameters passed ...

Resources

    • dynamically Loading External JavaScript Files(after reading, you can understand why the script tag is escaped in document.write)
    • passing JavaScript arguments via the src attribute(very systematic and orthodox discussion of how to pass parameters to JS files)
    • degrading Script Tags(John Resig can always be a mechanism to see a lot of problems)
    • On-demand Javascript(tired don't look, just glance at the line)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.