Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to import a javascript inside another javascript file

How to import inside JavaScript files and using Django to load another js.

Statements like these don't work:

import { PolymerElement, html } from '{% static "@polymer/polymer/polymer-element.js" %}';
import '{% static "@polymer/app-layout/app-drawer/app-drawer.js" %}';

And also these too:

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/app-layout/app-drawer/app-drawer.js';

// myapp-shell.js
import `${static_path}`;
//....
<!DOCTYPE html>
<html lang="en">
    <head>
        {% load static %}
        <script src="{% static 'node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js' %}"></script>
        <script src="{% static 'node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js' %}"></script>

        <!-- Loading app-shell -->
        <script>
            var static_path = '{% static "my-icons.js" %}';
            console.log(static_path);
        </script>
        <script type="module" src="{% static 'mycomponents/myapp-shell.js' %}"></script>
    </head>
    <body>
        <myapp-shell></myapp-shell>
    </body>
</html>

Is there is a way to do that without bundling the code in one big file, nor calling all files may be needed in the html file. Thank you

like image 313
Nomad Avatar asked Sep 21 '18 16:09

Nomad


1 Answers

I searched that for a long time and the way I found to do that is:

inside your mains script use this function.

function include(file) { 
  
    var script  = document.createElement('script'); 
    script.src  = file; 
    script.type = 'text/javascript'; 
    script.defer = true; 
    
    document.getElementsByTagName('head').item(0).appendChild(script); 
    
} 

then load your script like this:

include('/static/js/your_js_file.js');

don't forget to register your static files directory in settings.py

example:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "your_folder of library"),
]
like image 72
José Augusto Avatar answered Oct 31 '22 18:10

José Augusto