How do I remove script element from the DOM in UI5? - javascript

I am trying to remove a script tag from the DOM in UI5. Here is my code and lang is parameter to the function that can change.
var something= document.getElementById("id");
if (lang.toLowerCase().indexOf("en") === 0 && !something) {
var s = document.createElement("script");
s.setAttribute(...);
s.setAttribute(...);
document.body.appendChild(s);
s.setAttribute(...);
s.setAttribute(...);
}else if(lang.toLowerCase().indexOf("en") !== 0 && something){
something.remove();
}else{
document.body.appendChild(something);
}
When ever something.remove() happens the functionality of script tag still displays in the webpage. I also get error when the code does document.body.appendChild(something);
The expected result is the script tag will be removed from the dom when something exists and lang is changed and added back when something is changed back to en.

The expected result is the script tag will be removed from the dom when something exists and lang is changed and added back when something is changed back to en.
Your code may or may not be removing the script element. You wouldn't be able to tell because removing the script element has no effect on the code that the script element loaded into the JavaScript environment. You can't "unload" code that's been loaded.
The script element is just a box the code comes in. Once the box has delivered the code to the JavaScript engine, the engine runs it and keeps anything that it creates around (although objects that nothing references can be garbage collected at some stage). The box is no longer needed, and removing it makes no difference.
Here's a simpler example in the browser:
<input id="btn" type="button" value="Click Me">
<script id="the-script">
function clickHandler() {
console.log("clickhandler called");
const script = document.getElementById("the-script");
if (script) {
script.remove();
console.log("First click, removed `script` element");
}
}
document.getElementById("btn").addEventListener("click", clickHandler);
</script>
You can't remove the code that the script element loaded.
You can write the code so that you can disable whatever code the script element loads and re-enable it later, by using a flag or unregistering/re-registering event handlers, etc.

Related

Dynamically generated script tag does not execute after it is appended to the head tag [duplicate]

I am trying to load a certain script after page load executes, something like this:
function downloadJSAtOnload(){
var element = document.createElement("script");
element.src = "scriptSrc";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
And while this script seems to execute and download 'scriptSrc', and append it right before the end of the body tag, it yields the following message (not an error) in the console (chrome)
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
What does this even mean? And am I supposed to do something differently? Even though I get the expected behavior?
An asynchronously loaded script is likely going to run AFTER the document has been fully parsed and closed. Thus, you can't use document.write() from such a script (well technically you can, but it won't do what you want).
You will need to replace any document.write() statements in that script with explicit DOM manipulations by creating the DOM elements and then inserting them into a particular parent with .appendChild() or .insertBefore() or setting .innerHTML or some mechanism for direct DOM manipulation like that.
For example, instead of this type of code in an inline script:
<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>
You would use this to replace the inline script above in a dynamically loaded script:
var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);
Or, if there was no other content in the container that you needed to just append to, you could simply do this:
var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';
A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.
In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.
You can also call
document.open() before document.write()
call
document.close()
when you're done.
It may not be best practice for a real webpage but for testing etc.. can be used.

Does this not work because I can't use a script in a div?

I am making a website with a program editor, for users to make HTML programs.
I usually test this out by inputting <script> alert("Hi!"); </script> into the body input area, but no alert comes. As you can see from the code, the result is the script ending up inside the div.
So do scripts work in divs? If they do, here's my code (the important part, at least):
This is my script to run when I press the "Run!" button:
<script>
function onclick(){
document.getElementsByTagName("head")["0"].innerHTML += eval(document.getElementById("editorHead").value);
document.getElementById("result").innerHTML = eval(document.getElementById("editorBody").value);
}
</script>
This is the code for the input areas & run button (omitting the text between them & class attributes):
<textarea id="editorHead" rows="20"></textarea>
<textarea id="editorBody" rows="20"></textarea>
<div id="result"></div>
<button onclick="onclick();">Run!</button>
I tried changing the onclick's name to run, and that made the clicking work (before that the button wouldn't turn blue when you clicked it), but that was it.
The asked question is do scripts work in div's. Yes <script></script> tag content executes inline where it appears in the document.
However, it always executes in the document context. Meaning this === document. So to bind to the div's onclick method (the way you handle ui events in javascript) you need to find the div :
document.findElementById("my-div-id").onclick = function(e) {
// do something
};
Note this clobbers the default behavior for the element if there is a default click behavior (like on an a tag)
Also to be more clear on the expected behavior. Do this
<script>
function doSomething() {
alert();
}
</script>
<button onclick="doSomething()">Button</button>

Div is not created before javascript run

I have a question about javascript/html.
First, I have this:
var post = document.body.getElementsByClassName("post");
var x=post[i].getElementsByClassName("MyDiv")[0].innerHTML;
I get from the debugger that x is not defined, it doesn't exists.
This javascript function runs onload of the body. I am sure that I gave the right classnames in my javascript, so it should find my div.
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Is it possible that my function can't find the div with that classname because of this reason?
Is there a solution?
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Browsers create the DOM progressively as they get the markup. When a script element is encountered, all processing of the markup stops (except where defer and async have an effect) while the script is run. If the script attempts to access an element that hasn't been created yet (probably because its markup hasn't been processed yet) then it won't be found.
This javascript function runs onload of the body.
If that means you are using something like:
<body onload="someFn()"...>
or perhaps
<script>
window.onload = function() {
someFn();
...
}
</script>
then when the function is called, all DOM nodes are available. Some, like images, may not be fully loaded, but their elements have been created.
If it means you have the script in the body and aren't using the load event, you should move the script to the bottom of the page (e.g. just before the closing body tag) and see if that fixes the issue.
Okay, instead of calling functions with
body onload, use jQuery's ready() function, or, if you don't want to use jQuery, you can use pure javascript, but this is up to you:
// jQuery
$(document).ready(function() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
});
// JavaScript
window.onload = function initialization() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
}
A few side notes, I don't know what the use of innerHTML
is, and also if you're doing a for loop with i then definitely
post that code, that's kind of important.
After some discussion, my answer seems to have worked for you, but you can also place your script at the end of your body tag as #RobG has suggested.

Removing a script tag with a specific content using jquery

I have a page that i dont have access to its an obvius site. I would like to remove a script html tag with a content. For now i have this but is not working. I am using userscripts like coding!
function main(){
var def = $('script[type="text/javascript"]').html();
$('script[type="text/javascript"]').each(function() {
if (def == 'document.write("<scr"+"ipt type=\'text/javascript\' src=\'http://storing.com/javascripts/"+(new Date()).getTime()+"/3e155555e1b26c2d1ced0f645e_1_1.js\'></scr"+"ipt>")')
$('script[type="text/javascript"]').remove();
}
}
UPDATE:
<script type="text/javascript">document.write("<scr"+"ipt type='text/javascript' src='http://somedomain.com/javascripts/"+(new Date()).getTime()+"/3e1a0cd37f25a6e1b26c2d1ced0f645e_1_1.js'></scr"+"ipt>")</script>
This is the whole script what i want to remove... it inserts a div that i am removing right now i just wanted to know if there is any other method. BUt as i see the only is the hosts file thing :)
I don't believe this will work, since a loaded script will already have run.
That said, you probably want something like this:
$('script').each(function() {
if (this.src.substring(0, 31) === 'http://storing.com/javascripts/') {
$(this).remove();
}
});
It's impossible to match the <script> tag based on the output of .html() because that only returns the contents of the element, and not the outer <script> element nor the element's attributes.
When a script is loaded in a page, it is evaluated and executed by the browser immediately after. After the script has been executed, the content of the script tag is irrelevant.
You might be able to achieve what you want by unbinding the events which might have been loaded by the script. Are there any events you want to disable?
If the script is in a certain domain and you want to block all traffic to it, you could add the following entry to your hosts file:
127.0.0.1 storing.com
This will prevent the request to reach it's destination.

Separating JQuery Scripts with Selectors in External file does not work?

I have a JQuery Selector and an event associates with it.I want to keep it in external file and just copy and directly save it. The thing which I see is that the external JavaScript that has the selector does not work. Can someone explain Why?
NOTE: I am able to use the same function within my HTML file but when externalize it. It just doesn't work .
The script that I have is as follows:-
$('#pervious').click(function() {
var presentSlide = $('.visible').attr('id');
var tempArr = presentSlide.split("-");
var persentSlideNo = tempArr[1];
var perviousSlideNo = Number(persentSlideNo) - 1; if (perviousSlideNo > -1)
{
var perviousSlide = "Slide-" + perviousSlideNo;
$('#' + presentSlide).fadeOut('slow',function(){
$(this).removeClass('visible').addClass('hidden');
});
$('#' + perviousSlide).fadeIn('slow',function(){
$(this).removeClass('hidden').addClass('visible');
});
}
});
How are you including this script?
Note that it needs to go below the definition of your id=pervious element, or it needs to go after it (e.g. document.ready), otherwise the element won't exist, and there won't be anything to bind to.
UPDATE
To restate, it needs to execute AFTER the pervious element gets created. Putting it in an external document is likely causing it to execute BEFORE the pervious HTML element is created, and therefore it doesn't work. You can put it in an external file, sure, just make certain that the element gets loaded, e.g.
$(document).ready(function() {
$.getScript('http://yoursite.com/extrascript.js');
});
After you have determined you are actually linking to it by doing an alert, wrap your code like so:
$(function(){
// place your code inside here for ready event
});
What you are doing is running your selector before the document is ready. The selector runs before the dom is there and there is no results in the selector so you don't attach anything.
You have to include scripts with the form of: (including the closure tag as such)
<script src="myexternal.js" type="text/javascript"></script>
Not any of these:
<script src="myexternal.js" type="text/javascript" />
<script src="myexternal.js" />
<script src="myexternal.js" ></script>
form or it will not always get rendered properly and thus not execute.
and of course, since you are using jQuery, you should put YOUR code AFTER the jQuery library link AND include your code in a document ready as others have demonstrated.

Categories