Reputation: 3896
I'm trying to insert jQuery and another JS file in an iframe. I was wondering whether it's possible, or are there some issues about that?
Let us say those pages are just running on the same domain name.
The parent page will try to override the elements inside an iframe using Javascript.
Then I need to add another jQuery library on the subpage (http://jsbin.com/esifez/2).
Any idea about this?
$(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://code.jquery.com/jquery-latest.min.js';
$("#main_iframe").contents().find("body").append(script);
});
Thank you
Upvotes: 3
Views: 7852
Reputation: 35995
In your demo link your iframe already contains javascript trying to access $
or jQuery
way before your find("body").append(script);
will ever get computed. So this will fire an error because $
doesn't exist yet. You either need to do one of two things:
Include the jQuery script tag in the head of your iframe's source manually. Considering you have jQuery code in your iframe source, why not do this anyway?
Don't have any script trying to access jQuery
or $
in your iframe's source, unless the references are within functions or separate scripts that will only ever be executed after you have inserted your jQuery script tag.
Basically for point number 2, don't have this directly in your iframe:
<script>
/// dolar wont exist yet
$(function(){
})
</script>
Instead do this in your parent code:
var insertScript = function(src){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
$("#main_iframe").contents().find("body").append(script);
}
$(function() {
insertScript('http://code.jquery.com/jquery-latest.min.js');
// any code in your iframe that relies on jQuery should be
// moved off into this file
insertScript('iframe-js-code-that-requires-jq.js');
});
However it still makes more sense to have the jQuery script tag already within your iframe source, and not to dynamically insert it.
Upvotes: 1