views:

322

answers:

5

Scenario: I have a Javascript-generated web page that someone else wrote a long time ago that I'd like to pretty up using jQuery. My goal is to clean up the Javascript generated html that someone else produces just by using some jQuery calls against that HTML, after it has been generated.

This will be much simpler than modifying the other person's Javascript directly, at least for now.

My first attempt was to just add in a script tag at the end of the HTML head that invokes the desired jQuery code.

    <script src="/someone-elses-js-generator.js" />
    <script>
    $(document).ready(function() {
        alert('the other stuff ran, now do the jquery cleanup');
        $('.foobar').css("display","none");
        $('.doobar').css("display","inline");
        /// ... so on and so forth ...
    });
    </script>

Problem: The above works just fine, but when I comment out the "alert" message. The jquery no longer performs the cleanup. Apparently, what is happening is that the alert msg box was delaying the run of the subsequent cleanup code, which is great, but without the alert, the jQuery seems to run before the other javascript has finished its output.

Question: Is there a way to get the jQuery clean-up code to run after the js-generator code, but without having to put an alert() box in there?

+1  A: 

You could put the

$(document).ready(function() { ... });

At the end of /someone-elses-js-generator.js or at the end of the manipulation logic in this file.

okoman
+1  A: 

You can delay your cleanup code upto some extend by using following JavaScript function:

setTimeout('JS Cleanup Code', number_of_miliseconds);
Sachin Gaur
A: 

You could also try calling the cleanup code a second later by using setTimeout();

Ramuns Usovs
+1  A: 

I think you probably need to look at why the other coder's code is being delayed. If it's not running immediately and there's no reason it can't you could wrap his functionality in an anonymous function and run it immediately.

(function() {
    /*
    Other coder's code here
    */
 })(); //run this function and the code inside it immediately.
Steerpike
+4  A: 

Perhaps $(document).ready() is not the right way to go.

How does the other script get triggered? If it's on a window.onload then it probably only starts after your jQuery has started.

You want to wait until the other script has stopped running. Probably the best way to do this is wrap your jQuery in a function and call it from the other script when you're sure it has finished.

meouw