Bigbob556677
Bigbob556677

Reputation: 2158

Pass Scripts/ Styles From DOM To Child iFrame

On my server I am rendering pages that all have the exact same script/ style tags (from the templating on the back end).

And any time I want to create a popup on the site, I create a modal with an iFrame inside of it with the src set.

This causes all of the script tags to be loaded to the client a second time, with the performance impact expected.

My goal is to have the scripts files for the main DOM to be accessible from within the iFrame without reloading them.

Ideally what I'd be able to do is pass a parameter to the server that tells it not to include the script tags in the rendered HTML, and then "push" those scripts and styles from the client directly into the iFrame.

Is something like this possible to where I can maintain the functionality of document.ready and other API's while not having to reload all of the scripts and styles from the server?

Upvotes: 4

Views: 666

Answers (1)

vrintle
vrintle

Reputation: 5586

My goal is to have the scripts files for the main DOM to be accessible from within the iFrame without reloading them.

Kindly note that it is not recommended due to security reasons. It is better to reload the contents or make use of AJAX (which, of course loads the content) as @Pavan said. But, to answer the question, here is my approach

Once you've loaded your DOM (having inline scripts and styles), you can do

window.onload = function() {
    let styleTags = [ ...document.getElementsByTagName('style') ];
    styleText = styleTags.map(eachStyle => eachStyle.outerHTML).join('');
    // mapping each style tag to simple html text

    let scriptTags = [ ...document.getElementsByTagName('script') ];
    scriptText = scriptTags.map(eachScript => eachScript.outerHTML).join('');

    let myIFrame = document.getElementById("myIFrame");
    let doc = myiFrame.contentDocument;
    doc.body.innerHTML += styleText + scriptText;
}

This is only applicable as far as your DOM and iFrame has same domain. I expect you've the same domain for them, by default. Also, external scripts can't be accessed using this approach, they've to be loaded each time.

Upvotes: 3

Related Questions