简体   繁体   中英

What does the hash (#) mean after a .js file?

这里哈希(#)的意义是什么,它与.js文件有什么关系:

<script src="foo.js#bar=1"></script>

The hash after the script is used by the embedded script for configuration. For example, have a look at the provided example (facebook):

1. window.setTimeout(function () {
2.    var a = /(connect.facebook.net|facebook.com\/assets.php).*?#(.*)/;
3.    FB.Array.forEach(document.getElementsByTagName('script'), function (d) {
4.        if (d.src) {
5.            var b = a.exec(d.src); //RegExp.exec on the SRC attribute
6.            if (b) {
7.               var c = FB.QS.decode(b[2]); //Gets the information at the hash
8.               ...

In the script, each <script> tag line 3 is checked for occurrences line 5 of the hash line 2 at the attribute. Then, if the hash exists line 6 , the hashdata is extracted line 7 , and the function continues.

I doesn't do anything in terms of loading the script. What I am guessing is, the script itself looks for its own script tag, and picks out the piece after the hash (bar=1), and uses it to configure its behavior somehow. To do this, they probably have to loop through all script tags and match against the src attribute.

它可能在引用的.js文件中使用,读取原始URL并提取参数(例如使用window.location和解析#之后的内容)。

The part after the hash in a URL is know as a fragment identifier . If present, it specifies a part or a position within the overall resource or document. When used with HTTP, it usually specifies a section or location within the page, and the browser may scroll to display that part of the page.

In relation to the JavaScript file, the author of the program is in all probability using it as a method to pass arguments to the file. However, this method should not be used. URLs may contain query strings which serve the same purpose.

Nevertheless, it's never a good idea to embed arguments to the URL of a JavaScript file because for every different set of parameters the URL is cached again which is a waste of memory. Instead, it's better to set the query string on the URL of HTML page which contains the script itself. This is because JavaScript has a built in property to access the query string of the web page: location.search . You may read more about it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM