简体   繁体   中英

Javascript help - slowing page down

I'm not experienced in Javascript, so apologies if this is a basic question, but I have a js script in the head of my application that is slowing down the page loading time (eg examplepage.php). The code is below:

<script type="text/javascript">
$(document).ready(function(){ 

  $("a").click(function(){

    $.get('getdata.php', function(data) {
            $('#getdata').html(data);
        });
  });

});
</script>

getdata.php runs a script that connects to another service via an API. On examplepage.php I have a link that once clicked activates the js script above which pulls in data from the API (via getdata.php). This feature works, but what I am finding is that on loading the page the js script runs anyway and therefore slows down the loading time of the page.

I don't want the script to be calling the API unnecessarily (ie. if the user doesn't click the link on examplepage.php). How can I stop this js script running?

Sorry if this doesn't make sense - I'm a JS beginner!

Many thanks,

Gregor

The script you use is semantically equivalent to this one (I've just assigned a name to the anonymous function you use for sake of clarity):

<script type="text/javascript">
function readyAction() {
    $("a").click(clickEvent);
}

function clickEvent() {
    $.get('getdata.php', function(data) {
            $('#getdata').html(data);
        }
}

$(document).ready(readyAction);
</script>

You can read it in this way:

$(document).ready(readyAction); means when the $('document') is full loaded ready (it is a simplification) then execute the function readyAction . Note that the function is addressed (there aren't the () after his name) and not executed at this line.

The readyAction function does just a thing: scan the DOM and find all the anchors $("a") and then hook to the collected elements an handler clickEvent for the onclick event.

The function clickEvent do the XHR connection, retrieve the data from server and then fill the div (or whatever the element is) with id getdata. It will be executed only when the user clicks on a link.

That's all.

You are not issuing extra unneeded XHR calls with this code.
I hope this had shed some light on the inner workings of that code.

EDIT
As pointed by Quincy, maybe the DOM you want to manipulate is quite large, or there are a lot of anchor elements and this may slow down your execution, it is a rare chance but maybe it is your case. You can try to restrict the scope of search done by jquery adding an id to the link you want to animate .

ie you can change $("a").click( in $("#loadpagedatalink').click( as far 'loadpagedatalink' is the id of the link you have to attach the click handler to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM