배상일
배상일

Reputation: 107

How to execute external .js from svelte kit

-/src
|-/lib
|  |- address.svelte
|
|-/routes
|  |-/test
|  |   |- +page.svelte
|  |- +page.svelte

I'm trying to load address component from /routes/test/+page.svelte. I'm using svelte kit to develop my service, and this file tree is built for example.

The address.svelte is like so. It's suppose to run external js file when I press the input square.

<svelte:head>
    <script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
    <script>
    window.onload = function() {
        document.getElementById("address").addEventListener("click", function() {
            new daum.Postcode({
                oncomplete: function(data) {
                    document.getElementById("address").value = data.address;
                }
            }).open();
        });
    }
    </script>
</svelte:head>

<div class="field">
    <div class="container">
        <div class="card">
            <div class="content">
                <h1>IGIS</h1>
                <h2>Address Here</h2>
                <br/>
                <form>
                    <div>
                        <label class="label" for="address">소재지(주소)</label>
                        <br/>
                        <input class="input" id="address" type="text" name="address" placeholder=" " readonly required>
                    </div>
                    <button type="submit">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>

and /routes/test/+page.svelte is like so

<script>
    import Address from "$lib/address.svelte";
</script>

<Address></Address>

However when I click the input square, the external js doesn't seems to be loading. How am I suppose to do it?

Upvotes: 0

Views: 1905

Answers (1)

Smilefounder
Smilefounder

Reputation: 599

You should write the login that use external js file inside onMount instead.

<script>
    import { onMount, onDestroy, beforeUpdate, afterUpdate } from 'svelte';    
    onMount(async () => { 
        // your code here 
    });
</script>

Upvotes: 2

Related Questions