Gets the path to the current JavaScript script file

Source: Internet
Author: User

Gets the path to the current JavaScript script file

Gets the path to the current JavaScript script file, which may be required under a specific scenario, such as writing a module loader or logging. There is no uniform method for all browsers, this article is described in several cases.

(1). Standard practice: src attribute of Document.currentscript object
For Firefox 4+, Chrome 29+, Opera 16+, Safari 8+.

var src = document.currentScript.src;

(2). Extract the file path from the Stack property of the Error object
For ie10+, Safari 7-, Opera 15-.

varnewError(‘err‘);var‘‘;var/(?:http|https|file):\/\/.*?\/.+?.js/var src = (rgx.exec(stack)||[])[0‘‘;

If the browser does not support the error constructor, you can also get an Error object through Try...catch.

Listen to the OnError event to handle the Error object, as well as the principle. The 2nd parameter of the callback function for the onerror event is SRC. The code will not be posted.

(3). Find the src of the last script element in the Document.scripts collection
Applies to scenarios that are executed during script loading and does not apply to calls after script initialization is complete. There is no requirement for the browser.

var src = document.scripts[document.scripts.length1].src;

(4). Find the src of the script element with the ReadyState property interative in the Document.scripts collection
Suitable for ie9-. IE9 The following browsers, the Script.readystate property is interative to indicate that the script is executing.

vardocument.scripts, src;for (var1; i>=0; i--){    if‘interative‘){        src = scripts[i].src;        break;    }}

This article only provides the idea analysis, if needs to use in the product, needs to handle each kind of application situation judgment. Someone has created a JS function (getcurrabspath.js) to handle.

Gets the path to the current JavaScript script file

Related Article

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.