DEV Community

loading...
Cover image for Best way to use iframe on any website

Best way to use iframe on any website

stackfindover profile image Stackfindover ・Updated on ・3 min read

What is an iframe in HTML?

The <iframe> tag specifies an inline frame. An inline frame is used to embed another document within the current HTML document.
basically, an iframe is used to add another webpage to the same page.

Hello, guys In this tutorial we will try to solve the mentioned query. and also we will learn the best way to use iframe on any website.

Common Query

  1. How to use an iframe
  2. How to load an iframe on click
  3. The Best way to use an iframe

First, we need to create three files index.html, style.css and youtube-iframe.js { a JS file} then we need to do code for it.

How to use iFrame Step:1

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Best way to use iframe in website</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="style.css" />
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Oswald&display=swap" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="youtube-iframe.js"></script>
</head>
<body>
    <div class="iframe-outer">
        <div class="simple-iframe">
            <h2>Before Optimize</h2>
            <iframe width="424" height="238" src="https://www.youtube.com/embed/OaEds7xQmkw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="optimize-iframe">
            <h2>After Optimize</h2>
            <div class="youtube-player" data-id="OaEds7xQmkw"></div>
        </div>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

How to use iFrame Step:2

Then we need to add code for style.css which code I provide in the below screen.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: 'Oswald', sans-serif;
}
body {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f2f4f6;
  overflow: hidden;
}
.iframe-outer {
  display: flex;
  column-gap: 20px;
}
.youtube-player img {
  object-fit: cover;
}
.iframe-outer > div {
  position: relative;
}
.play {
  height: 72px;
  width: 72px;
  left: 40%;
  top: 45%;
  background: url(play.png) no-repeat;
  cursor: pointer;
  position: absolute;
}        
Enter fullscreen mode Exit fullscreen mode

How to use iFrame Step:3

Then we need to create a JS file, in my condition, I have a JS file { youtube-iframe.js } add below code inside the JS file.

document.addEventListener("DOMContentLoaded", function(){
    var div, n, 
    v = document.getElementsByClassName("youtube-player");

    for(n =0; n < v.length; n++) {
        div = document.createElement("div");
        div.setAttribute("data-id", v[n].dataset.id);
        div.innerHTML = labnolThumb(v[n].dataset.id);

        div.onclick = labnolIframe;
        v[n].appendChild(div);
    }
})
function labnolThumb(id) {
    var thumb = '<img width="424" height="238" src="https://img.youtube.com/vi/OaEds7xQmkw/hqdefault.jpg" alt="youtube">', 
    play = '<div class="play"></div>';
    return thumb.replace("ID", id) + play;
}

function labnolIframe() {
    var iframe = document.createElement("iframe");

    iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.dataset.id + "?autoplay=1");
    iframe.setAttribute("frameborder", "0");
    iframe.setAttribute("width", "424");
    iframe.setAttribute("height", "238");
    iframe.setAttribute("allowfullscreen", "1");
    this.parentNode.replaceChild(iframe, this);
}
Enter fullscreen mode Exit fullscreen mode

How to use iFrame Video Output:

Fixed Navbar Codepen Output:

JavaScript Tutorial For Beginners

  1. How to Create a Stopwatch in JavaScript
  2. How to create a custom right click menu
  3. How to create a digital clock in JavaScript

Discussion (19)

pic
Editor guide
Collapse
manuthecoder profile image
π™ΌπšŠπš—πšžπšƒπš‘πšŽπ™²πš˜πšπšŽπš› • Edited

One reason I don't ever use iframes in HTML is because of it's security vulnerabilities!

  • You may get a submittable malicious web form, phishing your users' personal data.
  • A malicious user can run a plug-in.
  • A malicious user can change the source site URL.
  • A malicious user can hijack your users' clicks.
  • A malicious user can hijack your users' keystrokes.

And it also causes bad user experience

  • It tends to break the browsers' "Back" button.
  • It confuses visually impaired visitors, using screen readers.
  • It confuses users, suddenly opening the iframe content in a new browser window.
  • Content within the iframe doesn't fit in and looks odd.
  • Content within the iframe is missing since the source URL changed.
  • Navigation of the site in the iframe stops working.
  • Every in a page requires increased memory and other computing resources.

Solution: Use AJAX instead of Iframes!

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       document.getElementById("el").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "file.php", true);
xhttp.send();
Enter fullscreen mode Exit fullscreen mode

Just don't use iframes too much ;)

Collapse
stackfindover profile image
Stackfindover Author

I agree, but this article only improves web page speed, because by using this method we load iframe after clicking on the element.

Thanks for suggestion :)

Collapse
michaelandreuzza profile image
michael-andreuzza • Edited

So true.

May I ask you, what would you use in this app instead of iframes?

I was using images but it looked bad.

Collapse
manuthecoder profile image
π™ΌπšŠπš—πšžπšƒπš‘πšŽπ™²πš˜πšπšŽπš›

Ok, in this case, an Iframe would probably be the best option.
Just make sure that only your domain can iframe it ;)

Thread Thread
michaelandreuzza profile image
michael-andreuzza

Yeah, us actually coming from a folder in that project.
Thank you Manu!

Thread Thread
Collapse
absolute001 profile image
Absolute001

What about the sandbox mode in iframes?

Collapse
manuthecoder profile image
π™ΌπšŠπš—πšžπšƒπš‘πšŽπ™²πš˜πšπšŽπš›

That works, but still, keep in mind that hackers can "intercept" data in iframes,
Basically hotlinking the site, and tracking keystrokes for example.

A way to prevent this is inserting this in your .htaccess file

header set x-frame-options SAMEORIGIN
Enter fullscreen mode Exit fullscreen mode
Thread Thread
absolute001 profile image
Absolute001

It's just a personal feeling or nowadays,front end developers must have some skills in security field? Are best practices enough to guarantee a safe navigation to our user?

Thread Thread
manuthecoder profile image
π™ΌπšŠπš—πšžπšƒπš‘πšŽπ™²πš˜πšπšŽπš›

Are best practices enough to guarantee a safe navigation to our user

Well, technically, yes, but it's a good practice to write secure code, no matter what you are building!

Also, It's also not just front end devs who need to consider security, it's also backend too ;)

But this article is useful if you're embedding a youtube video in an iframe.

Otherwise, I prefer AJAX, since it "embeds" smooth, and clean. It doesn't restrict scrolling.

Thread Thread
absolute001 profile image
Absolute001

How can I use AJAX to achieve the same thing of Iframes? πŸ€”πŸ€”πŸ€”

Thread Thread
manuthecoder profile image
π™ΌπšŠπš—πšžπšƒπš‘πšŽπ™²πš˜πšπšŽπš›
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       document.getElementById("el").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "file.php", true);
xhttp.send();
Enter fullscreen mode Exit fullscreen mode
Thread Thread
manuthecoder profile image
Thread Thread
absolute001 profile image
Absolute001

Thank you! ❀️

Collapse
madza profile image
Madza

Although completely different technologies, the iframe tag has always reminded me of something like adobe flash. Never felt pretty confident using it, as well as had a lot of headaches on sizing and responsiveness, etc.

Collapse
stackfindover profile image
Stackfindover Author

But this article is useful if you're embedding a youtube video in an iframe.

Yes, actually this article for Embed youtube videos, if we have used it directly it increases the page load time,
So we can use this way it can decrease page load time because by using this method we load iframe on click element

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

What are the real benefits, besides the numbers?

Collapse
miga profile image
Michael Gangolf

no external request which might violate GDRP/DSGVO

Collapse
miga profile image
Michael Gangolf

Nice! For YouTube I use this: dev.to/miga/prevent-youtube-iframe... so I don't have to make changes to my HTML code