I would like to define a variable, which will include my filename only without any extension.
The example of my file is linked to the index.html page and it looks like this:
<script src="js/20231014.js" type="text/javascript"></script>
<script src="js/20211204.js" type="text/javascript"></script>
<script src="js/20230423.js" type="text/javascript"></script>
about 50 more files like these
so I want in my variable only the "20231014" extracted.
I found some nice solutions here:
How to get the file name from a full path using JavaScript?
from where I tried:
var filename = fullPath.replace(/^.*[\\\/]/, '')
but I got an error, that fullPath is not defined. That has led me to this link,
where I tried:
var fullPath = FileSystemEntry.fullPath;
but unfortunately, the error just changed, that fileSystemEntry is not defined.
My another approach was:
var fileurl = '/js/'.replace(/\.[^.]+$/, '')
where I got nothing
and finally
var fileurl = window.location.pathname;
where I got just index.html instead
Is there any swift solution for extracting the given filename from the link based in the other directory?
This code will do what you're after.
First we find the position of the last / character appearing in the
file-path.
Then we get the string that appears after the last / in the path.
Next we replace the '.js' part with nothing.
I've only performed a single check. That avoids printing an empty string for the script element that does all the work, since it's in the document and doen's have a source.
You'll need to add error-checking before this code is any good.
<head>
<script src="js/20231014.js" type="text/javascript"></script>
<script src="js/20211204.js" type="text/javascript"></script>
<script src="js/20230423.js" type="text/javascript"></script>
<script>
"use strict";
window.addEventListener('load', onLoad, false);
function onLoad(evt) {
let scripts = document.querySelectorAll('script');
scripts.forEach(scr => {
if (scr.src != '') {
let slashPos = scr.src.lastIndexOf('/');
let filename = scr.src.slice(slashPos + 1);
filename = filename.replace('.js', '');
console.log(filename);
}
});
}
</script>
</head>
Related
<html>
<head>
<script async src="https://www.googletagmanager.com/gtag/js?id=xxxxx">
</script>
<html>
replace value xxx by var get from config
<script async src="https://www.googletagmanager.com/gtag/js?id=Var">
I want to replace the value of the id in src of script with a variable that I get from conf file
any help?
As HTML is "read" by the web browser, you won't be able to simply add a variable to a <script> tag. You can accomplish this through pure Javascript by loading in the file dynamically as stated here: Dynamically load JS inside JS
Where id_number is the number you are attempting to add:
var url_string = 'https://www.googletagmanager.com/gtag/js?id=' + id_number
var script = document.createElement('script');
script.onload = function () {
//do stuff with the script
};
script.src = url_string;
document.head.appendChild(script);
I have a static script declaration as a requirement, is it possible to have its URL dynamically constructed once browser wants to download it?
<script async src='https://my-known-host.com/script.js?param1=<dynamicValue>'
</script>
This parameter is generated on the client and let's say I want it to be just a random number.
I want to generate random on client side because server caches pages and this request should have a unique random number every time paged is loaded (even from cache)
I need to have it statically declared in order to start the download right away (even before browser parsed to the line of declaration)
Is it possible?
Yeah, a common approach is to write a script that injects the script tag. Something like this:
<script type="text/javascript">
setTimeout(function(){
var a = document.createElement("script");
var b = document.getElementsByTagName("script")[0];
// this adds some number, for example
// you can tweak it to be a random number if you want
a.src = document.location.protocol +
"my-known-host.com/script.js?param1=" +
Math.floor(new Date().getTime()/3600000);
a.async = true;
a.type = "text/javascript";
b.parentNode.insertBefore(a,b)
}, 1);
</script>
I actually took this example script from an analytics provider (crazyegg.com), but Google Analytics does a similar approach. In other words, it's a common thing.
<head>
<script>
$("head").append($("<script>", {async: true, src: "test.js?params=" + Math.random()}));
</script>
<script async src="test.js?params=0.524902342"></script> <!-- parse-able result from the script below -->
</head>
Sorry, I provided jQuery, but this or a vanilla approach should get the job done. The trick is to run JavaScript in head that would append <script src="example.js?" + random></script> to head.
After the browser runs that, it would parse your parameterized <script> at the end of the head tag.
I tested it myself and my browser made a request to test.js?params=0.3607864086033945
Hope that solves it!
EDIT:
If you don't want the script to be at the end of head, you can also do this. Very important that you let the browser parse <script id="randScript" async></script> first.
<script id="randScript" async></script>
<script>
$("#randScript").prop("src", "test.js" + Math.random()); //jQuery
document.getElementById("randScript").src = "test.js" + Math.random(); //vanilla
</script>
I get a variable from the controller that is a java script code and want to init a variable of java script file with this data as a string.
What I mean is:
Model.TrialScript is equal to the string of:
<script type="text/javascript">var j = new Date();</script>
(I got it from the DB)
and then, I want to do the next thing in my js file:
var TrialScript = '<%= Model.TrialScript %>';
The problem is that TrialScript is not like I expect:
var TrialScript = '<script type="text/javascript">var j = new Date();
assuming I must get the js code as: <script type="text/javascript"> and not:
<script type=\"text/javascript\">, how can I solve this issue?
Another thing may helps: I want to run this script only when the user press a button (is called: button1)
Maybe is there an option to call this script from the js after the button is clicked without saving this script as a variable?
any help appreciated!
You can try that way:
var TrialScript = '<%= Model.TrialScript %>';
//remove script tags, get only the code
TrialScript = TrialScript.replace(new RegExp("^<script.*?>(.*)</script>"), "$1");
// transform the code as a JS function
TrialScript = new Function(TrialScript);
// associate to the button1
document.getElementById("button1").onclick = TrialScript;
I am including a .js file using < link > attribute.
<script type="text/javascript" src="script.js"></script>
i want to put a condition that it should not include more than once in a page.
how can i put such a condition in HTML only. If that is not possible using HTML only,then what are the other options i can use to put such condition.
I think it's not possible with HTML.
Use JavaScript.
// keep track of scripts
var scripts = { };
function includeOnce(s) {
// if the script is not included before
if (!(s in scripts)) {
// add script
var sc = document.createElement('script');
sc.src = s;
document.body.appendChild(sc);
scripts[s] = 1;
}
}
To include a script:
<script>{ include_once("script.js") }</script>
Unless your script executes codes when loaded it may be sufficient to ensure your JS files are cached. Then in the worst case you're only sending an if-modified-since query which has a small overhead, especially if HTTP pipelining is supported.
Create a global variable in your script.js file, something like :
var isIncluded = true;
And then include your script like so
<script>!window.isIncluded && document.write('<script src="script.js"><\/script>')</script>
...with right path.
For example. I have script called foo.js. I'd like to insert stylesheet declaration which I can do with following instruction:
$('head').append('<link rel="stylesheet" href="/template/foo.css" type="text/css" />');
Problem: I have to put full path to the stylesheet file. So instead of /template/foo.css I have to put: http://hostname/directory/template/foo.css. I can't set it statically beacause script can be placed in different servers and different locations. So it can be: http://foo.com/bar/foo.css or http://foo.com/foo.css.
It would be very useful if I can get path of foo.js file on the server. That would be good enough beacause then I could set stylesheet location based on the javascrpt's file.
I've always done:
$('body').append('<link rel="stylesheet" href="/template/foo.css" type="text/css" />');
instead of head
Ahh... sorry I just realised what your problem is. One strategy is to extract the path of the script from the DOM itself:
$('script').each(function(i,el){
var path = el.src.match(/^(.+)\/foo.js$/);
if (path) {
$('body').append('<link rel="stylesheet" ' +
'href="' + path[1] + '/foo.css" ' +
'type="text/css" />'
);
}
})
This is a common technique that I use to get the current script url:
var scriptUrl = (function() {
var scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1];
return script.src;
})();
It works basically because when the script is being executed, it is the last script tag on the DOM.
You can use window.location and obtain the path from that. For example for this page it is:
>>> window.location
http://stackoverflow.com/questions/2033742/how-to-insert-external-stylesheet-in-javascript-dynamically