Programmatically remove <script src="/unwanted.js".. /> reference - javascript

I have partial control of a web page where by I can enter snippets of code at various places, but I cannot remove any preexisting code.
There is a script reference midway through the page
<script src="/unwanted.js" type="text/javascript"></script>
but I do not want the script to load. I cannot access the unwanted.js file. Is there anyway I can use javascript executing above this refernce to cause the unwanted.js file not to load?
Edit: To answer the comments asking what and why:
I'm setting up a Stack Exchange site and the WMD* js file loads halfway down the page. SE will allow you to insert HTML in various parts of the page - so you can have your custom header and footer etc. I want to override the standard WMD code with my own version of it.
I can get around the problem by just loading javascript after the original WMD script loads and replacing the functions with my own - but it would be nice not to have such a large chunk of JS load needlessly.
*WMD = the mark down editor used here at SO, and on the SE sites.

In short, you can't. Even if there is a hack, it would heavily depend on the way browsers parse the HTML and load the scripts and hence wouldn't be compatible with all browsers.

Please tell us exactly what you can and cannot do, and (preferably; this sounds fascinating) why.
If you can, try inserting <!-- before the script include and --> afterwards to comment it out.
Alternatively, look through the script file and see if there's any way that you could break it or nullify its effects. (this would depend entirely on the script itself; if you want more specific advice, please post more details, or preferably, the script itself.

Could you start an HTML comment above it and end below it in another block?
What does the contents of unwanted.js look like?

You can remove a script from the DOM after it is called by using something simple such as:
s = document.getElementById ("my_script");
s.parentNode.removeChild(s);
This will stop all functions of the script but will not take it out of user's cache. However like you wanted it can't be used.

Basically you can't unless you have access to the page content before you render it.
If you can manipulate the HTML before you send it off to the browser, you can write a regular expression that will match the desired piece of code, and remove it.

Related

How to reload part of a web page using iframe instead of ajax?

The reason I don't want to use ajax to do this is because the part I want to refresh is actually a commenting plugin implemented by other. I just put a snippet of script they provided in my html code and it shows a commenting part under my articles. As it's not a live commenting one, I want to add a refresh button next to it to enable users to just refresh the commenting part to get the latest comments without need for reloading the whole page.
Therefore, I think maybe iframe is an option for me. But the problem is I need to specify the src attribute of iframe. I don't know what value I should use because all I have is just a snippet of script. Can someone give me any idea on this?
By the way, the code snippet is as follows:
<div id="uyan_frame"></div>
<script type="text/javascript" id="UYScript" src="http://v1.uyan.cc/js/iframe.js?UYUserId=1674366" async=""></script>
Just create a html page with the script you talked inside about and use this file in the iframe src attribute.
You can put the snippet above in an html file like this
<!DOCTYPE html>
<html>
<body>
<div id="uyan_frame"></div>
<script type="text/javascript" id="UYScript" src="http://v1.uyan.cc/js/iframe.js?UYUserId=1674366" async=""></script>
</body>
</html>
And then use that file as the src of your iFrame, which you can refresh using javascript.
That said, just because you can do something doesn't mean you should do something. This is a really hacky way of doing what you're trying to do. A few alternative options:
Understand what the script you're using is doing, and work with it. Judging by the name of the script and div in the snippet, it may be creating an iframe to begin with. If thats the case, why not just figure out what that iFrame is called using your browsers debug it and refresh it manually, or modify the script to do so?
Use a live updating framework- This may not be possible for you, I don't know your constraints, but there are plenty of great commenting frameworks out there that do live updates. For instance Disqus comes to mind. Other examples are facebook comments or you could embed a reference to an external site like branch
Use Ajax - I'm a bit unclear on whether this is your script that you're writing, or a 3rd party script. If it is your script, then use the generally accepted methods for doing this type of work, unless you have a really great reason not too. You'll get better support from others, you'll gain more generally applicable experience, and for the most part, best practices gain that name for a reason. People use "ajax" methods for live updating pages because its effective and useful. Frames have become much less common on the web because they're clunky and make it difficult for different parts of the page to interact. If you don't have a great reason not to use the common practice, its usually your best bet.
You could do this :
var iframe = document.getElementById('your_frame_id');
iframe.src = iframe.src;
set the iframe src to its value again, this will cause the frame to refresh, and will work with cross domain frames

Load pages via AJAX and execute javascript and CSS

I've been searching for a while now, but I can't figure out how to load an entire page via AJAX and still execute all javascript and css.
Mostly I just end up with the plain text without any CSS.
Is there a way to do this? I tried jQuery.get, jQuery.load and jQuery.ajax, but none really work like that.
I have a different solution. You may try it with an iframe. Use jQuery to append an iframe script including all relevant codes into some part of your page (like some div). This may do it for you including CSS, like;
$('<iframe src="your_page.html"/>').appendTo('#your_div');
Or you may try something like;
$('<iframe src="your_page.html"/>').load(function(){
alert('the iframe is done loading');
}).appendTo('#your_div');
I have solved similar problem as following.
Download the webpage over ajax
Iterate it over and find any <script> and </script> tags
Get content from within these tags as text
Create new <script> element and insert there the code
Append the tag to your webpage
Another thing is you will need to somehow call the script..
I have done it this way:
I set standardized function names like initAddedScript callback which I am calling after appending the script to the page. Same as I have deinitScript called when I do not need the code (and its variables,..) anymore.
I must say this is awful solution, which likely means you have bad application architecture so as I have had:)
With css is it the same, but you do not need any handlers. Just append the style tag to your documents head.
If the page you load doesn't have any style data, then the external stylesheets must have relative paths that are not correct relative to the invoking document. Remember, this isn't an iFrame - you aren't framing an external document in your document, you're combining one document into another.
Another problem is that loading your complete page will also load the doctype, html, head, and body tags - which modern browsers will cope with most of the time, but the results are undefined because it's not valid HTML to jam one document into another wholesale. And this brings me to the third reason why it won't work: CSS links outside of the head section aren't valid, and the misplaced head section caused by your haphazard document-in-document collage.
What I'd do for compliance (and correct rendering) is this, which would be implemented in the Success callback:
Copy all link elements to a new jQuery element.
Copy the contents of all script in the head section
Copy the .html() contents from the loaded document's body tag
Append the link elements (copied out in step 1) to your host document's head
Create a new script tag with your copied script contents and stick it in the head too
Done!
Complicated? Kind of, I guess, but if you really want to load an entire page using AJAX it's your only option. It's also going to cause problems with the page's JavaScript no matter what you do, particularly code that's supposed to run during the initial load. There's nothing you can do about this. If it's a problem, you need to either rewrite the source page to be more load-friendly or you could figure out how to make an iFrame suit your needs.
It's also worth considering whether it'd work to just load your external CSS in the host document in the first place.
I suppose you are looking for something like this:
your page div --> load --> www.some-site.com
After a quik search the closest solution seems to be the one by "And": Load website into DIV
You have to run a web server and create a proxy.php page with this content:
Then your JQuery load() function should be like this:
$("#your_div_id").load("proxy.php?url=http://some-site.com");
NB. I have tested this solution and it should not load all the CSS from the target page, probably you'll have to recreate them. For example the image files stored on the remote server will not loaded, I suppose due to authentication policy.
You will be also able to view only the target page without the possibility to browse the target site.
Anyway I hope this could be a step forward to your solution.
Get your entire webpage as text using ajax
document.open();
document.write(this.responseText);
document.close();
OR
document.documentElement.outerHTML = this.responseText;
But you need to change the path of css and js pages in original webpage if the resulting webpage is in another directory.

Refrashing the Javascript File without page refresh.

I am working on a very complex web site which is wizard based and have many JavaScript files included.
Now problem is if I pass through many step and at some later stage I find a JavaScript problem, as I fix it I have to load the page again and as I load the page again the Wizard will be started from step one again.
What I want is if I make JavaScript change in a file, there should be a possibility to refresh the JavaScript file through Firebug or something like it.
Thanks a lot.
No, not really. You could try to change the <script>'s src attribute to something like /your/script.js?timestamp=1234567890, but this doesn't give a reliable guarantee that the script will be loaded again.
You could add another script element into the DOM, but then you'd have two very similar scripts loaded at the same time, which may be problematic.

Is it OK to put javascript code anywhere in HTML code?

I see that Javascript code is normally in heading part of HTML code.
<head>
<script type="text/javascript" language="javascript" src="core.js"></script>
...
</head>
Is it OK to put the Javascript code in a body part of HTML code? I tested it, but it seems to work.
<body>
<script type="text/javascript" language="javascript" src="core.js"></script>
...
</body>
If so, why the examples of Javascript books put the javascript code in heading part?
If not, what's the difference between putting the javascript code in body/heading part?
Not only is it OK, it's actually better, since it lets the content come first.
If your viewers have a slow (eg, mobile) connection, it's better to send the actual content first, so that they can read it while the browser downloads the Javascript.
All the people saying it is better only applies if you are talking about at the bottom of the page (and that is an up for debate thing) from a code quality point of view, it is NOT ok to sprinkle script tags through your html. All references to javascript should be in a single place on the page, either the head (where they should be), or the very bottom (as a perf optimization)
Edit:
Basically, a web page is made up of 3 pieces; style (css), structure (html), and behavior (javascript). These pieces are all very distinct, so it makes sense to keep them as separate as possible. That way if you need to change some javascript, it is all in one place. If it is sprinkled through the file, it becomes much more difficult to find the code you are looking for, and that code basically becomes noise when you are just looking at structure.
It is the same arguments as why not sprinkle db access code all over your page. It has nothing to do with technical reasons, purely an architectural/design decision. Code that does different things should be kept separate for readability, maintainability, and by extension, refactorability (not sure if that last one is actually a word...)
You can do it, and people often do.
For example, people like to put their script tags just before the closing </body> to make web pages render quicker.
Also, if you do a script block after an element is created, you don't need to wait for DOM ready.
Be warned though, don't add, or remove an element from an unclosed ancestor in the markup tree (not including the script block's immediate parent element), or you will get the dreaded Operation Aborted error in IE.
Just something to add on:
I have preference of putting Javascript file right before </body>. My reasons being that:
Content can load and be shown first. If you load huge Javascript files first, which most are meaningless until the page is loaded, the user won't be able to see anything until the JS files are loaded.
Most Javascript code require to work with the UI can only run after the UI has been loaded. Placing the codes at the end of the html file reduces the need to use the onload event handler.
It is very bad habit to place Javascript snippets all over the HTML file. Placing all at the back of the HTML file allows you to manage your Javascript more efficiently.
It is legal according to the spec.
Most examples use them in the header as the headers come first and the browser will be able to parse the reference and download the JS files faster.
Additionally, these are links and are not part of the display, so traditionally, put in the header.
It is perfectly legal but there seem to be some differing opinions about it. Those who say to put all the javascript references in the head argue that the script is downloaded before the rest of the page become visible and dependent on it. So your user will not see an object on screen, attempt to interact with it and get an error because the javascript code is not yet loaded.
On the other hand, the argument goes that it takes longer to load all the script before the user sees the page and that can have a negative impact on perceived speed of your site.
JavaScripts inside body will be executed immediately while the page loads into the browser
Placing javascript at the end of the body will defer javascript load (ie: the page will render faster), but remember that any javascript function used for an event should be loaded before the event declaration, it is mainly because users may be able to fire an event before the page is completely loaded (so before the function is loaded)!
I used to put it in the head, then I've heard that it takes longer for the page to load so I started placing the scripts at the very bottom. However, I found out the most 'clean' way to do it is to place it in the head BUT you place the script inside a document.ready function. This way you have the best of both worlds. It is cleaner because it is in the head and it is not loaded before the content has been loaded, so there aren't any problems performance wise either.
With jQuery for instance, you can do it like this:
$(document).ready(function() {
alert('test');
});
The alert will only popup when the page has been fully loaded, even though the script is in the head.

Optimal location for javascript includes

I've read that it is better to place your <script> tags at the end of the document. The argument for doing this appears to be that the browser will stall rendering the page below a script tag until it has loaded and and executed the script. If your script tag is at the top of the page, rendering is stalled for a while, which is bad.
However, I am not sure if this is really true any more.
Looking around, I normally see the following locations...
In the <head> of the page or Just inside the <body> tag
Stackoverflow is an example of a site that puts the script tags in the head, and since they are normally rather obsessed with performance, I am starting to wonder if position in the page is important at all.
Last thing in the body element
The other common place to put javascript appears to be right at the very end of the <body> element. I am assuming this means that the page can render while the javascript downloads and gets on with doing its thing.
But which is better?
Does anyone have any thoughts or advice on this? I am looking to try and get our pages to perform and appear to the user as quickly as possible.
Does it matter? What are the advantages of being at the top of the page? Bottom of the page?
It really depends.
There is no catch all answer for this because it depends on what your javascripts are acting on.
Putting scripts at the end of the page is sometimes needed if your acting on a DOM element that needs to be loaded for the script to run. Say you want to focus on a control and your script is:
var mytext = document.getElementById("mytext2");
mytext.focus();
Well in this case you would want it to execute at the end of the page, after mytext2 control has already been loaded by the browser. This is less important for script blocks that only contain functions that are called by events.
If you have a big .js file that contains libraries of functions you may also want to put that at the end of the page so the browser will load the page faster before loading the large .js file.
Google analytics suggests putting their tracker at the end, to make sure the page has been delivered before you count the hits, but in some cases it suggests putting the script into the header too, it works both ways.
So, rule of thumb for me is, HEAD scripts for everything except things that execute in-line and act on DOM objects, or large scripts that you want to load after the page.
Rick Strahl just wrote a great blog on placement of Javascript in .net too:
The only validating way is to include it on the top (in the <head> section), but in the bottom will be faster to load - the rest of the page will load faster if you have script near the bottom, giving the user better response and making the experience better.
The problem is that most web browser stop rendering the HTML of the page until they've fetched and parsed all JavaScript code so far. So if you have a slow-loaded .js file included in the <head>, no HTML will be rendered and images will not even start to download before the .js have been downloaded and parsed, therefore frontend engineers propagate for putting the scripts as far down in the code as possible.
I usually just set a far-future Expires header for my .js files so they are cached in the browser for a long time and then include them in the <head> section. This gives good performance and doesn't look ugly :-)
But if you are serving external .js libraries (that are on other servers than your own), you will probably want them in the bottom because you can't change the Expires-header for other servers and you canät know that the other server always will be responsive.
yeah. Put Scripts at the Bottom
I think the size of the js file is much more important than the location of javascript. I always set highter number of the con-current connection to make sure they download in parallel.
I believe it's better to place script tags just before the closing body tag. Because:
Elements are blocked from rendering if they are below the script.
In IE6, IE7 resources in the page are blocked from downloading if they are below the script.
From this article. Also Yahoo's performance rule 6 is Move Scripts to the Bottom
Google Analytics always used to say to put the script tag at the bottom of the page. I believe the rationale was that if the Google servers ever went down, the page would fail to load if it were in the head (only for IE probably).

Categories

Resources