Obtain the path of the current Javascript script file

Source: Internet
Author: User

Obtain the path of the current Javascript script file
Obtain the path of the current Javascript script file

Obtain the path of the current Javascript script file, which may be required in specific scenarios, such as writing module loaders or logging. There is no uniform method for all browsers. This article describes several situations.

(1). Standard Practice: src attribute of document. currentScript object
Applicable to Firefox 4 +, Chrome 29 +, Opera 16 +, and Safari 8 +.

var src = document.currentScript.src;

(2). Extract the file path from the stack attribute of the Error object
Applicable to IE10 +, Safari 7-, and Opera 15 -.

var e = new Error('err');var stack = e.stack || e.sourceURL || e.stacktrace || '';var rgx = /(?:http|https|file):\/\/.*?\/.+?.js/, var src = (rgx.exec(stack)||[])[0] || '';

If the browser does not support Error constructor, try... Catch to get an Error object.

Listen to the onerror event to process the Error object. The 2nd parameter of the callback function of the onerror event is src. The Code will not be pasted.

(3). Find the src of the last script element in the document. scripts set.
It is applicable to execution during Script Loading and not to calls after script initialization. No browser requirements.

var src = document.scripts[document.scripts.length - 1].src;

(4). Find the src of the script element whose readyState attribute is interative in the document. scripts collection.
Applicable to browsers earlier than IE9-. IE9. If the script. readyState attribute is interative, the script is being executed.

var scripts = document.scripts, src;for (var i = scripts.length - 1; i>=0; i--){    if (scripts[i].readyState === 'interative'){        src = scripts[i].src;        break;    }}

This article only provides an analysis of ideas. If you need to use it in a product, you need to handle the judgment of various applicable situations. Someone created a JS function (getCurrAbsPath. js) for processing.

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.