skip to Main Content

I want to write a generic Header and Footer that will be loaded into every html file i want, so when i want to modify either one, it will be modified on all the pages.

From the research I’ve done, I found that you can do that with jQuery by doing:

$(document).ready(function () {
    $('header').load('header.html')
    $('footer').load('footer.html')
})

And it worked. I’ve been building my page using it, in combination with Live Server (the VS Code extension), everything was great until i tested it by opening it from File Explorer. And it doesn’t work like that. It gives me the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file: path/to/src/header.html. (Reason: CORS request not http).

I understand that it has something to do with security policies. Is there some kind of workaround or I will have to copy-paste the header and footer into every file and just deal with it this way? And why does it work via Live Server and doesn’t work when I open it statically.

I have to mention that even though I know some JS, those are my first jQuery lines of code and I am not sure how it works under the hood.

2

Answers


  1. To make a javascript request, you need to make to the same website you are or to another website that allows it (though Access-Control response headers), but when you open using the file explorer, it’s not a server that is giving the files, the browser is justing opening from the machine, so there is no response headers and the browser cannot validate (you can see this in the Network tab in Chrome Developer Tools)

    enter image description here

    But when you open with the Live Server, then it is a normal server:

    enter image description here

    So you are good, when you deploy your application to the web it will be a server and it will work.

    Login or Signup to reply.
  2. This is a workaround I’ve used for personal projects because I like to use vim.
    If you have Python installed on your machine, you could try the following:
    Open up Windows PowerShell.
    cd to the directory your source files are at, then run python -m http.server
    This should result in a message similar to Serving HTTP on :: port 8000 (http://[::]:8000/) ...
    Next, go to your browser and insert this as your url localhost:port … ie: 127.0.0.1:8000

    If you edit files, refreshing the page should update the page with the new changes. If the page does not update, sometimes you have to clear cached images and files (for google CTRL + SHIFT + DEL will take you to where you can clear them)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search