How to execute a javascript before dom is ready? - javascript

I need to execute a javascript before the page is start to load? how can i do it? Atfirst my script should execute, after completion of script, if i need i should load the page else i shouln't load it. For example if my script redirect to another page i shouldnot load the current page else i should load it.

Do it server side ...
The logic you present, seems to fit better at the server side, if you really want to avoid the loading of the page completely..

simply write your script in the script tag as a first element in body tag:
-- updated --
for hiding other page elements, use div with full width and height, if you want to show the page, hide the div, that will fix the problem

You can't run a script before the page loads (without messing up the document type), but you can put the script early in the page, i.e. in the head section.
You can't stop the page from loading until your script has finished. The page will continue to load in the background, but it will not render until the script has finished.
If you do a redirect in your script, the page will stop loading, but what's already loaded will render while waiting for the new response to arrive.

Script tags are execute as soon as they are encountered. Just put your script tag early, and then use a redirect if your condition is true. Hooking the window.onload event handler is how you get Javascript to trigger on load.

Is it possible for you to serve a page initially which contains merely the JavaScript which you need to execute within an HTML document? You can then request the page you want based on the result of the JavaScript.

You could use the jQuery load() method to load a part of a page conditionally, which is not running script before the DOM is ready, but may achieve what you want to do.

Related

Deleting script tag is still working

I have 2 questions.
First,
I have a script tag (not jquery, my own js file) in my page. Then I run my page via apache in browser and delete that tag but the page is still working. why? I also delete all cache and not reload the page.
[delete in browser Elements window]
Second,
What happen when I put two script tag with same name (one in my localhost and another in file system) ? Which one will work?
After the browser loads the code from a <script> tag, it is loaded into the VM and kept there. If it saves some data or functions into global variables, they are independent from the DOM, just like e.g. the window object.
All event listeners sent by the code will also persist such removal, effectively meaning the JS is undisturbed by your actions. After a script has been run, it's almost impossible to "turn it off" and remove it from the webpage in a generic way.
If that's your code and you simply want to stop its execution, provide cleanup methods using e.g. removeEventListener to stop the browser from calling your code.

why is waiting until the page is loaded to execute this code important

Why is waiting until the page is loaded to execute this code important ?
window.onload = function () {
//javascript code
}
Most Javascript functions are intended to modify the content or structure of the DOM, but trying to affect the document programmatically should not be undertaken until the document is fully loaded. The onload event fires after the target document is loaded, thus ensuring that the code attached to the event is capable of affecting the corresponding document.
It is important, but you can also not use it.
You need to wait for the page to load when scripts need to modify/read elements in the page (they need to exist, and while the page is loading they don't exist yet): if you don't interact with the page, you don't need to use window.onload.
window.onload will execute the code once everything is loaded. This comes into importance when you need any element in the page to be present in the page for the script to execute.
eg: You are trying to alert a value in a textbox which has a default value and we have a script to alert this. Now this script should be executed once all the elements have been loaded. putting this code within the window.onload will ensure that it is loaded before execution.
on the other side if you do not need anything to be loaded for the script to run it need not be in the window.load.

How to detect that document loading has started through javascript?

I want to detect when the document has just started to load, so that I can make an ajax call right away...which will determine whether I need to navigate to another page or not. I don't want to wait for the entire page to load before firing the ajax, and then, possibly navigating away from this page on the basis of the result of this ajax request.
just put code in the head of the document, no?
or at the start of the body.
<script type="text/javascript">
function pageLoad() {
// Initialization code here, meant to run once.
}
</script>

How to capture the refresh inside of an iframe from parent document?

Here's the case:
We have a file upload page. We didn't want to reload the page once the upload is done, so we put the form inside of an iframe. The form inside of an iframe posts to itself and returns json when it's done. How can we capture that response? When upload is done, the iframe reloads, so in other words, how do we capture when the iframe is reloaded?
Assume these:
we cannot print/return anything except the json object (so no js code to call the function in a parent document.)
we cannot use ajax since you cannot post files using ajax
we cannot append javascript code inside of iframe, because once the form inside of iframe is submitted, the page gets reloaded and we lose the appended js code.
Any ideas?
UPDATE - Seems like the solution is super simple (found it somewhere online):
<iframe onload="alert(window['upload_iframe'].document.body.innerHTML);" ...></iframe>
This way, it will fire the alert whenever page inside of an iframe is reloaded. Now it's just matter of differentiating JSON object from HTML code, which is pretty simple. Thanks for everyone for a great advises!
Have you tried appending an "onload" listener to the iframe element to see if when the iframe source is changed it's triggered? That might be a solution. If it doesn't work, then I don't think you have a choice but to execute a top level function from the iframe result.
update
Since you don't have control over the response from the servlet, perhaps you could build a PHP median that communicates with the servlet and takes the raw json it gets and then returns what it needs to execute a parent window javscript function and passing the json to that function.
This way you control the output.
You could check whether the content of the iFrame has changed by performing a timed check of the inner text of the iFrame document against whatever it was last time you checked ( or a hash of it if the document is large ) and then once it has changed you could try parsing the content as JSON to check it is the expected response.
Alternately you could use AJAX to check whether the upload has completed on the server side and once the server confirms that it has finished uploading you can then check the iFrame content.

Reload a javascript widget based on a time interval

http://jsfiddle.net/4B2Bc/1/ <- the link to the widget
I have this javascript widget, which I want to reload every 60 seconds so the content on it is refreshed. However the problem is that whenever I use set timeout or anything else within the widget or outside the widget, the whole screen goes black when the widget refreshes.
In the debug window I can see that the json file for the new content is retrieved with the right content but it doesnt apply.
So the only other method I was left was to keep on writing the <script type="text/javascript" src="http://domainsoutlook.net/wjs/12_61532/" charset="utf-8"></script> tag which reloads the whole js and refreshes the widget, but the problem with this is that it happens quickly and at once, not periodically.
Any solutions guys...I am willing to use jquery in the widget if it is going to help.
Your script erases the page because you're using document.write:
Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call.
And document.open:
If a document exists in the target, this method clears it.
So if you call document.write any time except when the document is being initially loaded, you'll replace the entire document with what you write.
Don't use document.write to do your updates, just use a bit of AJAX to reload some new data from your server and then replace just the parts you need to replace using what ever DOM manipulation or jQuery techniques work best.
Once you have that working, use setTimeout or setInterval to arrange calls to your server for fresh data.
using jquery you can set an interval, which is like a timer.
$(function() {
setInterval( "refreshWidget()", timeinmilliseconds );
});

Categories

Resources