Force browser to reload javascript files - javascript

I tried like this
<script type="text/javascript" src="myfile.js"?+Date.now()></script>
In browser it is showing as it is.
I want to add some timestamp to each js files.
i.e.,
<script type="text/javascript" src="myfile.js"?+5671836294></script>
Thanks in advance.

You can't randomly stick JavaScript anywhere you like in HTML.
When you are in the middle of an HTML start tag you can either:
End the tag with >
Write an attribute
JavaScript does not belong there.
If you want to generate an HTML attribute value dynamically when the element is created, then you must create the entire element with JavaScript.
e.g.
<script>
var s = document.createElement("script");
s.src = "myfile.js"?+Date.now();
document.head.appendChild(s);
</script>
… but you'd probably be better of solving this problem by properly configuring your HTTP headers for the script instead.

Refresh the page or rewrite the script tag and append it to the bottom of the body.
But once a page is loaded, it is loaded. You have to redeclare to overwrite.

Related

Disable script tag in html file or change script tag type/src using javascript

I want to disable the script tag or if its possible to change script src or type in this script using javascript?
<script type="text/javascript" src="./1.js.download"></script>
I can't add id in this code.
please help and feel free to ask anything if you don't understand
How about removing it altogether? The example is a simple function that get an element by the given selector and remove it. FYI if you don't want the <script> to actually load, then your'e out of luck. It'll be parsed as long as it's in the HTML, there's no way to avoid it from loading by JavaScript.
In the example there are 3 <script> tags and the target is in the middle. document.querySelector("script") will stop at the first match so you'll need a more specific selector. To target the second tag I used script:nth-of-type(2). You can verify success using by F12
const killTag = selector => document.querySelector(selector).remove();
killTag(`script:nth-of-type(2)`);
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="./1.js.download"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
You can remove src from script tag like this:
s = document.querySelectorAll('script')
console.log(s[1])
s[1].setAttribute('src', '')
console.log(s[1])
<script type="text/javascript" src="./1.js.download"></script>
You will have maybe multiple scripts in your dom. then you have take a look which element it is and change the key from the collection. in this case the key was 1.
If you need to select specific script element you can get it by attribute like this:
let ok = document.querySelector('[src="./1.js.download"]');
//Then you can either change id or type:
ok.setAttribute('id', 'ok');
ok.setAttribute('type', 'module');

Can't append script element to head

Current variant looks like that (I tried solution offered here: Can't append <script> element):
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head").append(s);
Previous variant was:
$("head").append($('<script type="text/javascript" src="js/properties.js"></script>'));
And both of them don't work. "properties.js" is also in "js" folder, but if I remove this part of path, it doesn't change anything.
I also tried to use ' instead " and check addBlock: I had it installed, but it's disabled on this page.
Changing "append" function to "appendChild" also didn't help.
"properties.js" contains just one line:
var PREFIX_URL = "http://localhost:8080/app-rest-1.0.0-SNAPSHOT";
And firstly I declare it in "main.js" to which I, in fact, try to connect this file.
Explain, please, what I'm doing wrong.
Add all your <script> tags right before the closing </body> tag, because when the browser encounters a <script> tag it begins downloading it and stops rendering of the page. So by placing them at the bottom of the page you make sure your page is fully loaded before trying to interact with the DOM elements. Also $("head") returns an array of all the <head> tags. You should also enclose your calls in a $(document).ready() function.
<!-- Your html tags here -->
<script type="text/javascript">
$(document).ready(function(){
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head")[0].append(s);
});
</script>
</body>
I made JSBin example. You can see in console that last script tag is the one you need. So the your code is correct.
If your IDE don't highlight 'var' - it may be error not in javascript. You can place it in a wrong place for example.
Can you provide link to a gist (or pastie.org or smth) for us to better understand your problem.
P.S. The code $("head")[0].append gives me undefined ( note to previous answer)

How do I change the Javascript src file on client side?

Within my body tag, I have this:
<script src="http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAkh87y8Hjhg76ty" type="text/javascript"></script>
Is it possible to add JavaScript or jQuery in the head of the page to change the "key" parameter in the script source. I am trying to do this before the render reaches the above tag.
It is not possible to change the src attribute before the render reaches the tag, because modern browsers will download and parse the script as soon as it reaches a script tag (in that particular format).
You can use the defer attribute to hold off execution of the script until after the DOM has completely loaded, but this attribute is only supported in IE 4+ and Firefox 3.5+.
why not dynamically create the script tag triggered by onload.
In onload: make the JQuery call, create the src url from the result, append the script tag.
I don't know that you could change the key parameter before that script is rendered but you could dynamically write the entire script tag like this:
var script = document.createElement('script');
script.setAttribute('src', 'http://maps.google.com/maps?file=api&v=2.x&key='
+ param_ssKey + '/');
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);

How can I append a new element in place in JavaScript?

I've created a JavaScript script that can be pasted on someone's page to create an iFrame. I would like for the person to be able to paste the script where they would like the iFrame to appear.
However, I can't figure out how to append the DOM created iFrame to the location where the script has been pasted. It always appends it to the very bottom of the body.
How do I append in place?
Mm. You could do:
document.write("<div id='iframecontainer'></div>");
document.getElementById('iframecontainer').innerHTML = '...';
But that feels ugly/wrong in a lot of different levels. I am not aware of any other alternatives, though.
EDIT: Actually, a quick google search revealed this artlcle which discusses why document.write is ugly and a nice alternative for the particular pickle you're in: Give your script tag an ID!
<script id="iframeinserter" src=".."></script>
And then you can get a reference to the script tag and insert the iframe before it:
var newcontent = document.createElement('iframe');
var scr = document.getElementById('iframeinserter');
scr.parentNode.insertBefore(newcontent, scr);
Paulo's answer can also be done without the ID, by simply looking for the last <script> element. This must be the script block we're in, because JavaScript guarantees all content past the closing tag of the current script block has not yet been parsed(*):
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
script.parentNode.insertBefore(d, script);
This can be put in an onload/ready function if you like, but if so the ‘var script’ must be calculated at include-time and not in the ready function (when that executes, more <script>s will have been parsed).
(*: except in the case of <script defer>.)
If the user can give an id of an element that will be where the iframe should be, then it would be possible to just use css to move the iframe to where it should be on the page.

How can I create a javascript badge or widget?

I want to create a javascript badge that displays a list of links. We host the javascript on our domain. Other sites can put an empty div tag on their page and at the bottom a reference to our javascript that would render the content in the div tag. How do you implement something like this?
I would give the SCRIPT tag an ID and replace the script tag itself with the DIV + contents, making it so they only have to include one line of code. Something along the lines of the following:
<script id="my-script" src="http://example.com/my-script.js"></script>
In your script, you can swap out the SCRIPT tag for your DIV in one fell swoop, like so:
var scriptTag, myDiv;
scriptTag = document.getElementById('my-script');
myDiv = document.createElement('DIV');
myDiv.innerHTML = '<p>Wow, cool!</p>';
scriptTag.parentNode.replaceChild(myDiv, scriptTag);
just as you say, have them put a div at the bottom of their page:
<div id="mywidget"></div>
then have them link to your javascript:
<script type="text/javascript" src="http://yourdomain.com/mywidget.js"></script>
then have them alter their body tag, or onload to call your script
<script type="text/javascript">
document.body.onload = loadYourWidget();
</script>
You do not necessary need an initial div to fill with you link list.
Simply create the div using document.write at the place where the script is placed.
<script type="text/javascript" src="http://domain.com/badge.js"></script>
... and in your script:
var links = [
'One',
'Two',
'Three'
];
document.write("<div>" + links.join(", ") + "</div>");
Another benefit is that you do not have to wait for the page to be fully loaded.
Like #Owen said, except why not craft your javascript so that
<script type="text/javascript" src="http://yourdomain.com/mywidget.js"></script>
does the work of populating <div id="mywidget"></div> on its own, thus negating the need for them to call loadYourWidget() from their DOM load if you include the script tag right after the mywidget div in the html source. This isn't really a best practice, but I think it'll work.
Example for your mywidget.js code:
document.getElementById('mywidget').innerHTML = "<a href=''>LinkOne</a> <a href=''>LinkTwo</a>";
It took me some time to find this answer on Stackexchange because I was using different search terms. I believe that the link suggested there is a more complete answer than the ones already given here:
How to build a web widget (using jQuery)
It covers:
ensure the widget’s code doesn’t accidentally mess up with the rest of the page,
dynamically load external CSS and JavaScript files,
bypass browsers’ single-origin policy using JSONP.

Categories