Including html in html with jquery load not working

Viewed 913

I'm new to web dev so I feel like I'm missing something simple. I really just need someone to point out what I missed?

I'm trying to include a local html file into another html file using jquery load() function. I followed some suggestions from other stackoverflow posts. It seems like it should be very simple and work fine, but it's not working. I did add the jquery source into the head, and made sure the part where I'm inserting in the body included the correct div id. I don't need to insert a particular portion of the local html, just the whole thing. That html is just text and only includes <p> tags and similar things.

Here's the code:

<html>
<head>
    <meta charset="utf-8" />
    <title>letters on the road</title>
    <link rel="stylesheet" type="text/css" 
    href="../assets/css/style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script> 
    $(function(){
        $("#includedContent").load("text-012518.html"); 
    });
    </script> 
</head>
<body style="font-family:Andale Mono Regular">
    <div id="includedContent"></div>
    <a href="../index_v2.html">home</a>
</body>
</html>

I feel like jquery load seemed the cleanest option. I did try using the object tag, but it puts the text in a tiny scrollable box in the corner of the window. I'm not familiar enough with css to fix it, so still hoping that jquery load will work well.

My code above doesn't throw error, it just doesn't include anything at all from the external html. (The text in the external html did show up with object so I don't think it is a problem with the external html itself.) I've also tried the code without the $(function(){}); wrapper and it also doesn't work.

what shows up on the page

1 Answers

Most of the stack overflow solutions (Answer 1, Answer 2 and many more) do not work. The solutions implemented with Jquery .load() or XMLHttpRequest fails (at least on chrome) due to CORS issue. Work around will be to disable the security by adding --disable-web-security flag or using a CORS chrome extension, which both are only suitable for testing and not on a production application.

Access to XMLHttpRequest at 'file:///.../text.html' from origin 'null' has been blocked by CORS policy: 
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

These two approaches work -

  • Use <object> tag -

<object data="test.html"></object>

  • Use iframe tag -

<iframe src = "test.html" height="80px" width="500px" >

My approach would be to use Jquery/vanila javascript to load the html using the object tag. Add the script tag to the bottom of the page. Looking for more answers.

<script>
document.getElementById("includedContent").innerHTML='<object data="text.html"></object>';
</script>
Related