Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a page via Ajax into Div Best Practice?

I'm using the method below to load a remote page into a div I have on the page.

$('#result').load('www.myurl.com/results.html');

I'm curious, is it a bad practice to load an entirely formatted HTML page within another page? My concern is more towards loading css or additional javascript includes that might overwrite other elements on the primary page.

I haven't experienced any issues during my initial tests, I'm just not sure if this is the best practice.

To Clarify: If I have a primary page like so

<html>
    <head>
       <script src="jquery.js"></script>
       <link href="mycss.css" rel="stylesheet" type="text/css">
    </head>
    <body>
       <div id="remoteContainer"></div>
       <script>
          $('#remoteContainer').load('www.myurl.com/results.html');
       </script>
    </body>

And results.html code that looks like this:

<html>
    <head>
       <script src="jquery.js"></script>
       <link href="myResults.css" rel="stylesheet" type="text/css">
    </head>
    <body>
       <header>        
           <h1>My Results Page</h1>
       </header>
       ...
    </body>

Will the CSS and JS overwrite each other,or will the pages function as 2-separate entities?

like image 822
TheJason Avatar asked Mar 26 '13 21:03

TheJason


1 Answers

This will work fine and the browser will handle it properly. From the jQuery docs:

... browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

However, it's probably better practice to specify the element in the returned HTML that you want to insert:

$('#remoteContainer').load('www.myurl.com/results.html #containerDiv');
like image 113
Jivings Avatar answered Oct 28 '22 23:10

Jivings