开发者

Run javascript after page load

setup_account ui-mobile-viewport ui-overlay-c

When a page i make loads like this:

var location    =   location.href+"&rndm="+2*Math.random()+" #updatecomment0>*"
$("#updatecomment0").load(location, function(){});

I have multiple scripts running on the updatecomment0 div:

<div id="updatecomment0">
    <div id="javascript1">hi<开发者_如何学C;/div>
    <div style="float:right;" class="javascript2">delete</div>
</div>

I don't know how to make this other JavaScripts run after page load.

Can someone please tell me how to with this.

Thank you


Use $(document).ready().


Use jQuery, you can do this very easily.

jQuery(document).ready(function(){
    alert('Your DOM is ready.Now below this u can run all ur javascript');
});


Here is a sample layout for you

<script type="text/javascript">
    $(document).ready(function(){
        /// here you can put all the code that you want to run after page load
        function Javascript1(){
            //code here
        }

        function Javascript2(){
            // code here
        }

        $("#btnOK").live('click',function(){
            // some codes here
            Javascript1();
            Javascript2();
        });

    });
</script>

<div id="MyDiv">
    <input type="button" id="btnOK" value="OK"/>
</div>


write code inside ready

jQuery(document).ready(function(){

// write here
});

suggestion : use live or bind


Unless you need javascript to do something before the page is loaded, add your scripts to the bottom om the html document, just before the body end tag. The page will load faster, and you can do whatever you need to, right in the js file, without the document ready functions.

If the scripts is the last to load, the DOM is already guaranteed to be "ready".


$(window).load(function() {
    // code here
});


$(document).ready() is all you needed.


You can make JavaScript wait for a specified time using the setTimeout method:

.setTimeout("name_of_function()",time_in_millis);


I hope this can help you too, I had a similar issue and I fixed it by calling the following just after loading the content in the page (like after an AJAX request for a page to be shown inside a div):

(function($) {
 $(document).ready(function() {
  // your pretty function call, or generic code
 });
}(jQuery));

Remember to not call this in the document you load, but in the function that load it, after it as been loaded.


Using vanilla Javascript, this can done thusly:

<html>
<head>
<script type="text/javascript">

// other javascript here

function onAfterLoad() { /*...*/ }

// other javascript here

</script>
</head>
<body>

<!-- HTML content here -->

<!-- onAfterLoad event handling -->
<div style="display:none;"><iframe onload="onAfterLoad();"></iframe></div>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜