'jQuery .load() run the same as body displayed
i have a project that needs to include external html to my page. so this file will be included to many page. I'm using jQuery here. Let me show some code:
$(document).ready(function(){
$('myBody').load('myExternal.html');
});
It runs of course... But that external file is loaded AFTER my page has been loaded. What i want is, when my page has been loaded, the external file is dispayed too ,directly, without wait some time. Anyone can help? I appreciate all of your helps
Solution 1:[1]
The reason your external file is being delayed is because you're only firing the .load()
function after the entire base document is already loaded and ready. That means your external file will be late by at least the time of the request, plus any overhead from jQuery or anything else.
The jQuery .ready()
method "offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate." That means when your load function runs, the document has been displayed to the user, and you'll have to wait for the browser to get the external file.
Loading page sections using Ajax client-side can result in slow, cumbersome, or unusable web pages, because the user needs to wait for those sections before they can use the website. Additionally, the sections may just not load at all, for any number of reasons. Many privacy-focused browsers disable Javascript, some older browsers might not support features your code is using, the client's internet could be spotty, or anything else. Having the entire page as part of the base document from the server is much better.
That said, look into Apache Server-Side Includes (equivalent for nginx, if you use that). This isn't a Javascript solution, but should accomplish what you want. Instead of the client loading them at runtime, the sections will be included before the file leaves the server, saving on a ton of overhead time and possible issues.
If you really want to use Javascript for this, consider displaying a "please wait" until the entire page, including external sections, is loaded. After that, remove the "please wait" and show the page.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aryn Thernium |