I'm a beginner in developpement, and for my personal knowledge I try to make a website in html, css and js.
The website get a random project from Artstation with Axios at a Json and display it on the web page, I have 24 random image generated
I share you the Js code :
const images = document.getElementsByClassName("pic");
const redirect1 = document.getElementsByClassName("redirect1");
const redirect2 = document.getElementsByClassName("redirect2");
randomButton.addEventListener("click", function () {
for (i = 0; i < images.length; i++) {
images[i].src = "small_square.png";
loadImages(i);
}
});
async function loadImages(i) {
const response = await axios.get("https://www.artstation.com/random_project.json");
images[i].src = response.data.cover.smaller_square_image_url;
redirect1[i].href = response.data.permalink;
redirect2[i].href = response.data.permalink;
}
Don't juge it I know is not verry clean, now I explain my problem, I made the code like that for generate the 24 images simultaneously, the problem is if I not open my console in google chrome he load the function one by one, this is a issue I don't have with firefox
I have made the result in video
Did you know how fix that ?
I have this simple angular app: janev.ga with a custom JS file for the countdown (I am using the classycountdown script).
THE PROBLEM: when I run it locally everything loads great, however, once I deployed it to the server I realized it doesn't work the same as my localhost testing. What I mean by that is when I try to access it online, it would never load the JS script on the first go, even though there are no errors. I have to refresh the page and only then would the countdown script start working...
The way I use it in the component is by declaring it in angular.json (the custom.js file):
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
"src/assets/js/custom.js",
"src/assets/js/jquery.classycountdown.min.js",
"src/assets/js/jquery.classycountdown.js",
"src/assets/js/jquery.knob.js",
"src/assets/js/jquery.throttle.js"
]
, then I use it in the component like this:
declare const myDate: any;
export class AppComponent implements OnInit {
myDate = myDate()[0];
scnds = (myDate()[0] * 86400) - myDate()[1];
toSec = {
seconds: this.scnds
}
}
And this is the custom.js:
function myDate(){
var rightNow = new Date();
// var theDate = rightNow.toISOString().slice(0,10).replace(/-/g,"");
var goLiveDate = new Date("08/22/2020");
var Result = Math.round(goLiveDate.getTime() - rightNow.getTime()) / (1000*3600*24);
var toTheSecond = (rightNow.getHours() * 3600) + (rightNow.getMinutes() * 60) + (rightNow.getSeconds());
return [Result.toFixed(), toTheSecond];
}
$(document).ready(function() {
var remainingSec = $('.countdown').data('remaining-sec');
$('.countdown').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + remainingSec
});
});
Can anyone suggest what may the problem be? Any input would be appreciated.
Thanks!
Note: This question is not a duplicate of other existing questions because this question does not use jsdom.env() function call which older version of JSDOM use.
File bar.js:
console.log('bar says: hello')
File foo.js:
var jsdom = require('jsdom')
var html = '<!DOCTYPE html><head><script src="bar.js"></script></head><body><div>Foo</div></body>'
var window = new jsdom.JSDOM(html).window
window.onload = function () {
console.log('window loaded')
}
When I run foo.js, I get this output.
$ node foo.js
window loaded
Why did bar says: hello output did not come? It looks like bar.js was not loaded. How can I make jsdom load the file in the script tag?
[EDIT/SOLUTION]: Problem solved after following a suggestion in the answer by Quentin. This code works:
var jsdom = require('jsdom')
var html = '<!DOCTYPE html><head><script src="bar.js"></script></head><body><div>Foo</div></body>'
var window = new jsdom.JSDOM(html, { runScripts: "dangerously", resources: "usable" }).window
window.onload = function () {
console.log('window loaded')
}
Go to the JSDOM homepage.
Skim the headings until you find one marked Executing scripts
To enable executing scripts inside the page, you can use the
runScripts: "dangerously" option:
const dom = new JSDOM(`<body>
<script>document.body.appendChild(document.createElement("hr"));</script>
</body>`, { runScripts: "dangerously" });
// The script will be executed and modify the DOM:
dom.window.document.body.children.length === 2;
Again we emphasize to only use this when feeding jsdom code you know
is safe. If you use it on arbitrary user-supplied code, or code from
the Internet, you are effectively running untrusted Node.js code, and
your machine could be compromised.
If you want to execute external scripts, included via <script
src="">, you'll also need to ensure that they load them. To do this,
add the option resources: "usable" as described below.
Given I was unable to reproduce the url-based solution from the code above...
Brutal bundle alternative : inline it all !
Read the various .js files, inject them as string into the html page. Then wait the page to load as in a normal navigator.
These libraries are loaded into _window = new JSDOM(html, { options }).window; and therefor available to your node script.
This is likely to prevent you from doing xhr calls and therefore only partially solve the issue.
say-hello.js
// fired when loaded
console.log("say-hello.js says: hello!")
// defined and needing a call
var sayBye = function(name) {
var name = name ||'Hero!';
console.log("say-hello.js says: Good bye! "+name)
}
main.js:
const fs = require("fs");
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
var NAME = process.env.NAME; // variable from terminal
var html = '<!DOCTYPE html><head></head><body><div>Foo</div></body>'
var _window = new JSDOM(html, {
runScripts: "dangerously",
resources: "usable" }).window;
/* ************************************************************************* */
/* Add scripts to head ***************************************************** */
var jsFiles = [
'say-hello.js'
];
var scriptsContent = ``;
for(var i =0; i< jsFiles.length;i++){
console.log(__dirname + '/'+ jsFiles[i])
let scriptContent = fs.readFileSync( jsFiles[i], 'utf8');
scriptsContent = scriptsContent + `
/* ******************************************************************************************* */
/* `+jsFiles[i]+` **************************************************************************** */
`+scriptContent;
};
let scriptElement = _window.document.createElement('script');
scriptElement.textContent = scriptsContent;
_window.document.head.appendChild(scriptElement);
/* ************************************************************************* */
/* Run page **************************************************************** */
_window.document.addEventListener('DOMContentLoaded', () => {
console.log('main says: DOMContentLoaded')
// We need to delay one extra turn because we are the first DOMContentLoaded listener,
// but we want to execute this code only after the second DOMContentLoaded listener
// (added by external.js) fires.
_window.sayBye(NAME); // prints "say-hello.js says: Good bye!"
});
Run it:
NAME=John node main.js # expects hello and good bye to john messages
Source:
https://github.com/jsdom/jsdom/issues/1914
https://github.com/jsdom/jsdom/issues/3023
Using JSDOM option url : file://${__dirname}/index.html could work, according to a source. If you test it, please report result here.
I have an angularJS quiz application that works fine on localhost. Once uploaded to a live server the app doesnt load and the console fires an error. I have no idea what could be wrong as the app is working locally. Here is the error:
Error: [$injector:modulerr] http://errors.angularjs.org/1.6.3/$injector/modulerr?p0=ng&p1=%5B%24compile%3Abaddir%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.3%2F%24compile%2Fbaddir%3Fp0%3Dng%2520%0AM%2F%3C%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A1%3A425%0Ac%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A16055%0Ay%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A16467%0AIc%2F%3C%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A1%3A1416%0Ap%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A1%3A1201%0Ay%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A16968%0ACe%2F%3C%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A3365%0Ainvoke%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A10908%0Ad%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A9758%0Ag%2F%3C%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A9905%0Ap%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A1%3A1011%0Ag%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A9667%0Aeb%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A11811%0Ac%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A3%3A373%0APc%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A3%3A686%0Aue%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A2%3A5429%0A%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A9%3A72076%0Ai%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-includes%2Fjs%2Fjquery%2Fjquery.js%2Cqver%3D1.12.4.pagespeed.jm.pPCPAKkkss.js%3A1%3A27444%0AfireWith%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-includes%2Fjs%2Fjquery%2Fjquery.js%2Cqver%3D1.12.4.pagespeed.jm.pPCPAKkkss.js%3A1%3A28213%0Aready%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-includes%2Fjs%2Fjquery%2Fjquery.js%2Cqver%3D1.12.4.pagespeed.jm.pPCPAKkkss.js%3A1%3A30004%0AK%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-includes%2Fjs%2Fjquery%2Fjquery.js%2Cqver%3D1.12.4.pagespeed.jm.pPCPAKkkss.js%3A1%3A30366%0A
Does anyone have any insights? I have developed the quiz as a wordpress plugin with some variables localized to the angular script.
I am using angular 1.6 with angular route. Some of my code is below:
(function(){
/*
* Declaration of main angular module for this appllication.
*
* It is named quiz and has no dependencies (hence the
* empty array as the second argument)
*/
angular
.module("quiz", []);
})();
Controllers:
(function () {
angular
.module("quiz")
.controller("quizCtrl", QuizController);
QuizController.$inject = ['quizmanager'];
function QuizController(quizmanager)
{
...
Controllers:
(function () {
angular
.module("quiz")
.controller("resultsCtrl", ResultsController);
ResultsController.$inject = ['quizmanager'];
function ResultsController(quizmanager)
{
var vm = this;
vm.quizmanager = quizmanager;
}
})();
CONTROLLER:
(function () {
angular
.module("quiz")
.controller("welcomeCtrl", WelcomeController);
WelcomeController.$inject = ['quizmanager'];
function WelcomeController(quizmanager)
{
var vm = this;
vm.quizmanager = quizmanager;
vm.activateQuiz = activateQuiz;
/*
* STARTING POINT OF APPLICATION. All the other views are hidden
*/
quizmanager.loadQuiz();
function activateQuiz()
{
quizmanager.changeState("quiz", true);
quizmanager.countdown();
}
}
})();
Based on your responses, heres where i think the problem lies:
FACTORIES:
(function () {
angular
.module("quiz")
.factory("quizmanager", QuizManager)
.filter('formatTimer', function () {
return function (input)
{
function z(n) {
return (n < 10 ? '0' : '') + n;
}
var seconds = input % 60;
var minutes = Math.floor(input / 60);
var hours = Math.floor(minutes / 60);
return (z(hours) + ':' + z(minutes) + ':' + z(seconds));
};
});
QuizManager.$inject = ['$http', '$timeout', '$httpParamSerializer', '$filter'];
......
I have modified the app and added the filter as a seperate module like so:
(function () {
angular
.module("quiz")
.filter('formatTimer', function () {
return function (input)
{
function z(n) {
return (n < 10 ? '0' : '') + n;
}
var seconds = input % 60;
var minutes = Math.floor(input / 60);
var hours = Math.floor(minutes / 60);
return (z(hours) + ':' + z(minutes) + ':' + z(seconds));
};
});
})();
The app still works in localhost but Im still getting an error:
Error: [$injector:modulerr] http://errors.angularjs.org/1.6.3/$injector/modulerr?p0=ng&p1=%5B%24compile%3Abaddir%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.3%2F%24compile%2Fbaddir%3Fp0%3Dng%2520%0AM%2F%3C%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A1%3A425%0Ac%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A16055%0Ay%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A16467%0AIc%2F%3C%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A1%3A1416%0Ap%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A1%3A1201%0Ay%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A16968%0ACe%2F%3C%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A3365%0Ainvoke%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A10908%0Ad%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A9758%0Ag%2F%3C%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A9905%0Ap%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A1%3A1011%0Ag%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A9667%0Aeb%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A4%3A11811%0Ac%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A3%3A373%0APc%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A3%3A686%0Aue%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A2%3A5429%0A%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-content%2Fplugins%2Feot_quiz%2Fpublic%2Fjs%2Fangular.min.js%2Cqver%3D1.0.0.pagespeed.jm.L2GCHQP8hk.js%3A9%3A72076%0Ai%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-includes%2Fjs%2Fjquery%2Fjquery.js%2Cqver%3D1.12.4.pagespeed.jm.pPCPAKkkss.js%3A1%3A27444%0AfireWith%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-includes%2Fjs%2Fjquery%2Fjquery.js%2Cqver%3D1.12.4.pagespeed.jm.pPCPAKkkss.js%3A1%3A28213%0Aready%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-includes%2Fjs%2Fjquery%2Fjquery.js%2Cqver%3D1.12.4.pagespeed.jm.pPCPAKkkss.js%3A1%3A30004%0AK%40http%3A%2F%2Fexpertonlinetraining.info%2Fwp-includes%2Fjs%2Fjquery%2Fjquery.js%2Cqver%3D1.12.4.pagespeed.jm.pPCPAKkkss.js%3A1%3A30366%0A angular.min.js,qver=1.0.0.pagespeed.jm.L2GCHQP8hk.js:1:425
Description
This error occurs when a module fails to load due to some
exception. The error message above should provide additional context.
A common reason why the module fails to load is that you've forgotten
to include the file with the defined module or that the file couldn't
be loaded.
Using ngRoute
In AngularJS 1.2.0 and later, ngRoute has been moved to
its own module. If you are getting this error after upgrading to 1.2.x
or later, be sure that you've installed ngRoute.
Monkey-patching AngularJS's ng module
This error can also occur if you
have tried to add your own components to the ng module. This has never
been supported and from 1.3.0 it will actually trigger this error. For
instance the following code could trigger this error.
angular.module('ng').filter('tel', function (){}); Instead create your
own module and add it as a dependency to your application's top-level
module. See #9692 and #7709 for more information
What version of AngularJS are you using? You might be running into the second issue description here.
I'm trying to do something like a C #include "filename.c", or PHP include(dirname(__FILE__)."filename.php") but in javascript. I know I can do this if I can get the URL a js file was loaded from (e.g. the URL given in the src attribute of the tag). Is there any way for the javascript to know that?
Alternatively, is there any good way to load javascript dynamically from the same domain (without knowing the domain specifically)? For example, lets say we have two identical servers (QA and production) but they clearly have different URL domains. Is there a way to do something like include("myLib.js"); where myLib.js will load from the domain of the file loading it?
Sorry if thats worded a little confusingly.
Within the script:
var scripts = document.getElementsByTagName("script"),
src = scripts[scripts.length-1].src;
This works because the browser loads and executes scripts in order, so while your script is executing, the document it was included in is sure to have your script element as the last one on the page. This code of course must be 'global' to the script, so save src somewhere where you can use it later. Avoid leaking global variables by wrapping it in:
(function() { ... })();
All browsers except Internet Explorer (any version) have document.currentScript, which always works always (no matter how the file was included (async, bookmarklet etc)).
If you want to know the full URL of the JS file you're in right now:
var script = document.currentScript;
var fullUrl = script.src;
Tadaa.
I just made this little trick :
window.getRunningScript = () => {
return () => {
return new Error().stack.match(/([^ \n])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)[0]
}
}
console.log('%c Currently running script:', 'color: blue', getRunningScript()())
✅ Works on: Chrome, Firefox, Edge, Opera
Enjoy !
The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target <script> tags with a [src] attribute.
/**
* Current Script Path
*
* Get the dir path to the currently executing script file
* which is always the last one in the scripts array with
* an [src] attr
*/
var currentScriptPath = function () {
var scripts = document.querySelectorAll( 'script[src]' );
var currentScript = scripts[ scripts.length - 1 ].src;
var currentScriptChunks = currentScript.split( '/' );
var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];
return currentScript.replace( currentScriptFile, '' );
}
This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.
Refining upon the answers found here I came up with the following:
getCurrentScript.js
var getCurrentScript = function() {
if (document.currentScript) {
return document.currentScript.src;
} else {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1].src;
}
}
// module.exports = getCurrentScript;
console.log({log: getCurrentScript()})
getCurrentScriptPath.js
var getCurrentScript = require('./getCurrentScript');
var getCurrentScriptPath = function () {
var script = getCurrentScript();
var path = script.substring(0, script.lastIndexOf('/'));
return path;
};
module.exports = getCurrentScriptPath;
BTW: I'm using CommonJS
module format and bundling with webpack.
I've more recently found a much cleaner approach to this, which can be executed at any time, rather than being forced to do it synchronously when the script loads.
Use stackinfo to get a stacktrace at a current location, and grab the info.file name off the top of the stack.
info = stackinfo()
console.log('This is the url of the script '+info[0].file)
I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.
// Get script file location
// doesn't work for older browsers
var getScriptLocation = function() {
var fileName = "fileName";
var stack = "stack";
var stackTrace = "stacktrace";
var loc = null;
var matcher = function(stack, matchedLoc) { return loc = matchedLoc; };
try {
// Invalid code
0();
} catch (ex) {
if(fileName in ex) { // Firefox
loc = ex[fileName];
} else if(stackTrace in ex) { // Opera
ex[stackTrace].replace(/called from line \d+, column \d+ in (.*):/gm, matcher);
} else if(stack in ex) { // WebKit, Blink and IE10
ex[stack].replace(/at.*?\(?(\S+):\d+:\d+\)?$/g, matcher);
}
return loc;
}
};
You can see it here.
Refining upon the answers found here:
little trick
getCurrentScript and getCurrentScriptPath
I came up with the following:
//Thanks to https://stackoverflow.com/a/27369985/5175935
var getCurrentScript = function() {
if (document.currentScript && (document.currentScript.src !== ''))
return document.currentScript.src;
var scripts = document.getElementsByTagName('script'),
str = scripts[scripts.length - 1].src;
if (str !== '')
return str ;
//Thanks to https://stackoverflow.com/a/42594856/5175935
return new Error().stack.match(/(https?:[^:]*)/)[0];
};
//Thanks to https://stackoverflow.com/a/27369985/5175935
var getCurrentScriptPath = function() {
var script = getCurrentScript(),
path = script.substring(0, script.lastIndexOf('/'));
return path;
};
console.log({path: getCurrentScriptPath()})
Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,
<script type=text/javascript src='/dir/jsfile.js'></script>
or
<script type=text/javascript src='../../scripts/jsfile.js'></script>
If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path
I may be misunderstanding your question but it seems you should just be able to use a relative path as long as the production and development servers use the same path structure.
<script language="javascript" src="js/myLib.js" />
I've thrown together some spaghetti code that will get the current .js file ran (ex. if you run a script with "node ." you can use this to get the directory of the script that's running)
this gets it as "file://path/to/directoryWhere/fileExists"
var thisFilesDirectoryPath = stackinfo()[0].traceline.substring("readFile (".length, stackinfo()[0].traceline.length - ")".length-"readFile (".length);
this requires an npm package (im sure its on other platforms as well):
npm i stackinfo
import stackinfo from 'stackinfo'; or var {stackinfo} = require("stackinfo");
function getCurrnetScriptName() {
const url = new URL(document.currentScript.src);
const {length:len, [len-1]:last} = url.pathname.split('/');
return last.slice(0,-3);
}