• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

component_js_dependencies 시 defer, async load

24.06.29 16:25 작성 조회수 37

0

안녕하세요 강의 잘 수강하고 있습니다.


django_components를 사용할 때
template 에서 {% component_js_dependencies %}로 js 로드시

해당 script를 async, defer로 로드할 수 있는 방법이 있을까요?

답변 1

답변을 작성해보세요.

0

안녕하세요.

component_js_dependencies 템플릿 태그에서는 각 Component 의 render_js_dependencies 메서드를 호출하여 "<script src=js경로></script>\n<script src=js경로></script>" 문자열을 생성합니다.

관련 소스 코드 : https://github.com/EmilStenstrom/django-components/blob/master/src/django_components/component.py#L173

위 소스코드를 보시면, render_js_dependencies 메서드 내에서 <script>{self.js}</script> 코드와 self.media.render_js() 코드를 통해 script 태그를 조합하여, script 태그 문자열을 조합하는 데요. 기본 구현에서는 script 태그에 src 속성 외에는 추가 속성은 지원하고 있지 않습니다.

이 script 태그에 async와 defer 속성을 추가하실려면, 각 Component 클래스의 render_js_dependencies 메서드를 재정의하신 후에, 아래처럼 문자열 변경으로 원하시는 속성을 추가해주실 수 있습니다.

@component.register("예시")
class ExampleComponent(component.Component):
    # 생략

    def render_js_dependencies(self) -> SafeString:
        html = super().render_js_dependencies()
        html = html.replace("<script", "<script defer")
        return mark_safe(html)

살펴보시고 댓글 남겨주세요.

화이팅입니다. :-)

채널톡 아이콘