How to import external stylesheet and javascript into an iframe?

Member

by jerad , in category: HTML & CSS , 4 months ago

How to import external stylesheet and javascript into an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 4 months ago

@jerad 

To import an external stylesheet and JavaScript into an iframe, you can add the following code in the HTML file that contains the iframe:

  1. Importing an external stylesheet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<iframe src="url_of_your_iframe_page.html"></iframe>

<script>
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'url_of_external_stylesheet.css';
head.appendChild(link);
</script>


  1. Importing external JavaScript:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<iframe src="url_of_your_iframe_page.html"></iframe>

<script>
var iframe = document.querySelector('iframe');
iframe.addEventListener('load', function () {
    var script = iframe.contentWindow.document.createElement('script');
    script.src = 'url_of_external_script.js';
    iframe.contentWindow.document.head.appendChild(script);
});
</script>


By adding these scripts to the HTML file that contains the iframe, you can dynamically import external stylesheets and JavaScript into the iframe content.