Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 11533
  • Last Modified:

Use Jquery to include an external HTML file and Javascript

I have found several Jquery codes that allow you to include the contents of an external HTML and place it within a <div> but if that external file contains Javascript then the Javascript will not work once loaded. I have also seen Jquery code to load external Javascript. So my question is how can I have Jquery both load my external file into a div AND have the Javascript included in that external file load and function?
0
KeneticImages
Asked:
KeneticImages
  • 9
  • 3
  • 2
1 Solution
 
EMB01Commented:
Why won't the JS work in your external file? Is your content type set right? Here's an easy article on using jQuery to load external HTML:
http://elearninglive.com/wordpress/2008/09/dynamic-loading-of-external-html-file-using-jquery/
0
 
KeneticImagesAuthor Commented:
When using HTTPRequest, which is what these other scripts use to bring in an external HTML file, the Javascript is not retained when you user (innerHTML) to place that external HTML all JS from the external file is ignored. It has nothing to do with the JS in the external file. The only way to bring in an external file and have it contain its external JS as well is to use (document:write) but then you cannot target a specific target, ie. An internal Div to place it in.

So, basically there are two ways to use AJAX to include an external file within your parent file... (document.write) and (innerHTML). Each type has its advantages and disadvantages. (document.write) automatically brings the scripts and the styles of the external document to the (parent) document, but does not allow dynamically including the external content: 'everything' is included while the page loads (with

<script type="text/javascript">
ajaxinclude('some_external_file.html')
</script>

...somewhere in the body.

The (innerHTML) method does allow dynamic includes, but does not automatically insert the external scripts and styles into the main file (in non-IE, (parts of) the external styles are preserved, though, during the transfer of the request) I think the main issue here is that IE does not support this method fully.

The only way I have found to do this is to make a call using HttpRequest, read the external file in and place it into a hidden div using document:write(), and then swap the data in and out of a specific div internally. This however requires that you pre-load each and every page on the onset that you are going to use.

I'm just thinking that there has to be a better way...

Here is a link to a site that explains in better detail what I'm talking about:
http://molendijk.110mb.com/include_with_write_and_inner/ajaxinclude_with_write_and_inner.html
 
0
 
EMB01Commented:
As I've read here:
http://www.dynamicdrive.com/dynamicindex17/ajaxcontent.htm

"Due to security limitations, the external pages loaded must be from the same domain as the encompassing page."

Maybe the same is true for this. Also, about IE - maybe you should check out prototype.js. Take a look at this article:
http://nodstrum.com/2007/02/27/ajaxcontentload/

These folks seem to have come across the same problem in IE 7, and the solution is here:
http://nodstrum.com/2007/02/27/ajaxcontentload/#comment-216
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
KeneticImagesAuthor Commented:
I have seen that info... the Javascript files and the HTML files are ALL local. ie. in the Same Domain. So that is not the issue.

I have also read the tutorials on nodstrum.com and again they give no explanation or help in regards to external javascript not being executed on the external HTML upon load. In fact the link to the comments section that you supplied was only addressing that some could not  see the external content at all... not the javascript attached to any external content.

The closest solution I have come to is here:
http://www.dynamicdrive.com/forums/showthread.php?t=13003
http://www.dynamicdrive.com/forums/showthread.php?t=17426

and here:
http://www.dynamicdrive.com/forums/showthread.php?t=27400

however, when I read this it is a bit above my head and I don't know the exact code I should be adding and subtracting.

The code that I am wanting to use on the external HTML files is this:
<script type="text/javascript">
$(document).ready(function(){
  swap_letter();    
});
      
function swap_letter() {
  var first_paragraph = $('div.drop-cap p')[0];
  if (!first_paragraph) return false;
  var node = first_paragraph;
  while (node.childNodes.length) {
    node = node.firstChild;
  }

  var text = node.nodeValue;
  var first_letter = text.substr(0,1);
  var match = /[a-zA-Z]/.test(first_letter);
  if ( match ) {
    node.nodeValue = text.slice(1);
    $('<img />')
        .attr('src','images/alphabet/' + first_letter.toLowerCase() + '.png')
        .attr('alt',first_letter)
        .addClass('fancy-letter')
        .prependTo( first_paragraph );
  }
}
</script>
Now according to the advice over at DynamicDrive the solution lies in adding the Javascript in the parent document and then using a polling procedure to activate it when your external document is loaded... I'm just not sure how.
0
 
EMB01Commented:
Quite frankly, that's a bit over my head, too. I wish I could help. Maybe you should open a new question with regards to "using a polling procedure" when an "external document is loaded." Again, I'm sorry I can't help.
0
 
KeneticImagesAuthor Commented:
No problem. It was worth a try.
0
 
sh0eCommented:
Take away the $(document).ready()

I am a little bit confused.  Are you using $(document).ready() for the code that is being dynamically loaded?  The DOM will already be ready long before you call $.load(), so the $(document).ready() will never fire.
0
 
KeneticImagesAuthor Commented:
Actually that code was written that way... I didn't add $(document).ready() to it...

I'm just trying to find out how I can apply this function to externally loaded content.

I'm now looking at the Jquery plugin "livequery" as a possible solution, but I don't know.
0
 
sh0eCommented:
load is asynchronous.  Use a callback to run the manipulations after the external page is loaded.

---aaa.html---
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $('div.drop-cap').load("aaab.html",swap_letter);
});
      
function swap_letter() {
  var first_paragraph = $('div.drop-cap p')[0];
  if (!first_paragraph) return false;
  var node = first_paragraph;
  while (node.childNodes.length) {
    node = node.firstChild;
  }
 
  var text = node.nodeValue;
  var first_letter = text.substr(0,1);
  var match = /[a-zA-Z]/.test(first_letter);
  if ( match ) {
    node.nodeValue = text.slice(1);
    $('<img />')
        .attr('src','images/alphabet/' + first_letter.toLowerCase() + '.png')
        .attr('alt',first_letter)
        .addClass('fancy-letter')
        .prependTo( first_paragraph );
  }
}
</script>
<div class="drop-cap">
</div>
 
---aaab.html---
<html>
<body>
<div>
<p>a b c d
</p>
</div>
</body>
</html>

Open in new window

0
 
KeneticImagesAuthor Commented:
OK... that worked! But how would I do the load from a link, instead of it embeded in the JS. Or better yet, how could I change this script to work as above. In this script it loads the #content of the caled page into the #content of index.html.

So a menu could call each file into index.html.... like so.
    <ul id="nav">
        <li><a href="index.html">welcome</a></li>
        <li><a href="about.html">about</a></li>
        <li><a href="portfolio.html">portfolio</a></li>
        <li><a href="contact.html">contact</a></li>
        <li><a href="terms.html">terms</a></li>
    </ul>

So... I hope you have an answer for me... :)

$(document).ready(function() {
						   
	$('#content').wrap('<div id="content-wrapper"></div>');
						   
	function pageload(hash) {
		if(hash) {
			$("#content-wrapper").load(hash + ".html #content",'',function(){
				$('#content-wrapper').show('normal');
				$('#load').fadeOut('normal');												   
			});
		} else {
			$("#content-wrapper").load("index.html #content"); //default
		}
	}
	$.historyInit(pageload);			   
 
	$('#nav li a').click(function(){
								  
		var hash = $(this).attr('href');
		hash = hash.replace(/^.*#/, '');
		hash = hash.substr(0,hash.length-5);
 
		$('#content-wrapper').hide('fast',function(){$.historyLoad(hash)});
		$('#load').remove();
		$('#wrapper').append('<span id="load">LOADING...</span>');
		$('#load').fadeIn('normal');
		return false;
		
	});
 
});

Open in new window

0
 
KeneticImagesAuthor Commented:
I figured out how to make the default page work on line 12 in the code above...

$("#content-wrapper").load("index.html #content",swap_letter); //default

But what do I need to add to line 7 to get it to work for the rest of the links?
0
 
KeneticImagesAuthor Commented:
I got it!!!!

I added it to line 9
$('#content-wrapper').show('normal',swap_letter);

Thanks sh0e!
0
 
KeneticImagesAuthor Commented:
er... actually line 8! :)
0
 
KeneticImagesAuthor Commented:
Thanks for your help... with your help I was able to get the code to work just like I wanted it to!
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 9
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now