Solved

Use Jquery to include an external HTML file and Javascript

Posted on 2008-10-10
14
11,504 Views
Last Modified: 2011-02-01
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
Comment
Question by:KeneticImages
  • 9
  • 3
  • 2
14 Comments
 
LVL 14

Expert Comment

by:EMB01
Comment Utility
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
 

Author Comment

by:KeneticImages
Comment Utility
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
 
LVL 14

Expert Comment

by:EMB01
Comment Utility
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
 

Author Comment

by:KeneticImages
Comment Utility
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
 
LVL 14

Expert Comment

by:EMB01
Comment Utility
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
 

Author Comment

by:KeneticImages
Comment Utility
No problem. It was worth a try.
0
 
LVL 16

Expert Comment

by:sh0e
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:KeneticImages
Comment Utility
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
 
LVL 16

Accepted Solution

by:
sh0e earned 145 total points
Comment Utility
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
 

Author Comment

by:KeneticImages
Comment Utility
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
 

Author Comment

by:KeneticImages
Comment Utility
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
 

Author Comment

by:KeneticImages
Comment Utility
I got it!!!!

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

Thanks sh0e!
0
 

Author Comment

by:KeneticImages
Comment Utility
er... actually line 8! :)
0
 

Author Closing Comment

by:KeneticImages
Comment Utility
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now