How to load external website into an using jQuery?

To load an external website into an <iframe> using jQuery, use the attr() method to dynamically set the src attribute of the iframe element. This approach allows you to change the iframe content programmatically after the page loads.

Basic Implementation

The attr() method in jQuery allows you to get or set any HTML attribute. For iframes, setting the src attribute will load the specified URL into the frame.

Example

You can try to run the following code to learn how to load an external website into an iframe ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $('#iframe').attr('src', 'https://www.qries.com');
        });
    </script>
</head>
<body>
    <h2>Loading External Website in iframe</h2>
    <iframe id="iframe" name="myIframe" frameborder="5" width="500" height="300"></iframe>
</body>
</html>

Interactive Example with Button

Here's a more interactive example that loads different websites on button clicks ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $('#btn1').click(function(){
                $('#myframe').attr('src', 'https://www.example.com');
            });
            
            $('#btn2').click(function(){
                $('#myframe').attr('src', 'https://www.google.com');
            });
        });
    </script>
</head>
<body>
    <button id="btn1">Load Example.com</button>
    <button id="btn2">Load Google</button>
    <br><br>
    <iframe id="myframe" width="600" height="400" frameborder="1"></iframe>
</body>
</html>

Important Considerations

Cross-Origin Restrictions: Many websites prevent themselves from being loaded in iframes using X-Frame-Options headers or Content Security Policy. If a site doesn't load, it's likely due to these security measures.

Responsive Design: Consider making your iframe responsive by using percentage widths and CSS styling instead of fixed pixel dimensions.

Conclusion

Using jQuery's attr() method provides a simple way to dynamically load external websites into iframes. This technique is useful for creating dynamic content areas that can display different external resources based on user interactions.

Updated on: 2026-03-13T19:16:59+05:30

40 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements