I have a page that includes various blocks of information retrieved from db. Those blocks are arranged into sections and currently all that code is withing a long PHP page, so every time I load a page, there’s a delay with its display. I would like to be able to load the page faster and place some sort of “loading…” or image placeholder in the section where the content will be loaded. I see it done frequently on other sites. How do I accomplish that? Do I need to break my long PHP page into:
-
Main layout page
-
Place each block with data from db into a separate page, and
-
Use includes to insert into main page.
How would I place “loading” while the content is being generated?
Just trying to better understand the process. I also use jQuery. Perhaps there’s a pluging that can help with this?
Thanks.
Include in your main layout page only those elements that you would like to be visible when the page initially loads. You should have placeholder elements with IDs that can be accessed via JavaScript where you would like content that you will be fetching from the server.
Use jQuery’s ajax function to load the content from a separate request to the server:
In your backend PHP script, simply
echoout the content that you want to show up. You can optionally pass the content back as a JSON object, which is a more preferred method but requires more processing on the client side (the object must be parsed first before it can be accssed. See PHP’s json_encode function and JSON.org for more info on JSON).Structured this way, it makes the most sense to me to make 1 ajax request per container that you would like to fill.
Please also check out the reference page for jQuery’s ajax function