Can you import JavaScript (or other non CSS) files using the @import CSS function?

161 views Asked by At

I know you can't do this on Chrome as I tried it and it failed. When I run the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
    <p>Test</p>
    <style>
        @import "script.js";
    </style>
</body>
</html>

with a 'script.js' file in the same folder I get the following error in the chrome console: image

My questions are:

  1. Is this the same for all browsers?
  2. Is there a workaround which allows you to import and run non .css files using the @import function?
1

There are 1 answers

0
Quentin On BEST ANSWER

Can you import JavaScript (or other non CSS) files using the @import CSS function?

The short answer is... no.

@import is built to import stylesheets. A common misconception is that you can import non-CSS files by doing the following:

@import url("chrome://communicator/skin/");

However, the only reason the line ending is dropped is because the URL for a native browser package need not actually specify a file; it can just specify the package name and part, and the appropriate file is chosen automatically (e.g. chrome://communicator/skin/). See here for details.

For more information, see the MDN docs here about @import.