Cara menggunakan UNLOADS pada JavaScript

28/01/2020    Maykhel David    1144    Website

Show

Cara menggunakan UNLOADS pada JavaScript

Hallo semuanya, pada kali ini kita akan membahas tentang javascript, lebih tepatnya tentang bagaimana cara memperingati user ketika ingin meninggalkan halaman website. Ya, disini kita menggunakan sebuah event yang cukup jarang digunakan namun fungsinya cukup penting. Event ini adalah beforeunload. Untuk lebih jelasnya bisa kalian lihat penjelasan dibawah ini.

Contoh Kode

window.addEventListener("beforeunload", () => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

Kegunaan

Peringatkan user sebelum mereka meninggalkan halaman. Kedengarannya seperti itu bisa sangat menjengkelkan, tetapi juga tidak dianggap menjengkelkan. Event ini digunakan di website tempat kalian biasa melakukan pekerjaan dan perlu menyimpannya secara berkala. Jika user belum menyimpan pekerjaan mereka dan akan muncul popup tersebut, kalian dapat menggunakan event ini untuk memperingatkan mereka. Dengan catatan, jika mereka menyimpan karya mereka, kalian harus menghapus event ini.

Cara Kerja

Jika kalian telah melampirkan event beforeunload ke halaman (dan melakukan hal-hal ekstra seperti yang ditunjukkan dalam situasi yang telah disebutkan di atas), user akan melihat popup yang meminta mereka untuk melakukan konfirmasi apakah mereka ingin "Tinggalkan" atau "Batalkan" ketika mencoba untuk meninggalkan halaman. Saat meninggalkan website mungkin disebabkan user mengklik sebuah link secara tidak sengaja, atau juga bisa merupakan hasil dari mengklik tombol refresh atau kembali pada browser.

MDN memperingatkan bahwa beberapa browser mengharuskan halaman untuk memberikan interaksi daripada tidak ada sama sekali:

    Untuk mengatasi munculan popup yang tidak diinginkan, beberapa browser tidak menampilkan beforeunload event kecuali jika halaman tersebut telah berinteraksi dengan sesuatu yang menjadi triggernya. Selain itu, beberapa browser tidak menampilkannya sama sekali.

Alternatif

Tidak perlu terlalu dipikirkan. Jika kalian memperhitungkan tentang user yang kehilangan data sebelum menyimpannya maka kalian cukup gunakan ini pada halaman tertentu saja. Sehingga jika mereka memilih untuk tetap, kalian harus jelaskan tentang apa yang harus mereka lakukan untuk memastikan bahwa mereka saat meninggalkan halaman.

Baiklah teman teman, demikian artikel kali ini yang membahas tentang penggunaan event beforeunload, semoga bermanfaat.

Javascript

Di sini kita belajar JavaScript, mulai dari nol dan lanjut terus hingga konsep yang mutakhir macam OOP.

Konsentrasi kita di sini tertuju ke bahasanya itu sendiri, dengan catatan lingkungan tertentu se-minimum mungkin.

29

New! Save questions or answers and organize your favorite content.
Learn more.

How can I unload a JavaScript resource with all its defined objects from the DOM?

Im developing a simple framework that enables to load html fragments into a "main" html. Each fragment is self contained and may include references to additional JS and CSS files. The JS and CSS resources are parsed and dynamically added to the html. When the fragment is removed/replaced from the DOM I want to remove its JS and CSS.

If I remove the script element in the example below, the functions defined in page1.js are still available.

<html>
  <head>
    <script src="page1.js" type="text/javascript"></script>
  </head>
<body>
...

Is there a way to unload page1.js objects from the DOM?

========= The test code I use =======

I tried the advice i got in the comments below; to delete the added objects using a cleanup function - but even this fails. The sources i used for testing:

<html>
<head>
<script type="text/javascript">
    function loadJSFile(){
        var scriptTag = document.createElement("script");
        scriptTag.setAttribute("type", "text/javascript");
        scriptTag.setAttribute("src", "simple.js");

        var head = document.getElementsByTagName("head")[0];
        head.appendChild(scriptTag);
    }

    function unloadJSFile(){            
        delete window.foo;
        delete window.cleanup;
        alert("cleanedup. typeof window.foo is " + (typeof window.foo));
    }
</script>
</head>
<body>

  Hello JavaScript Delete

  <br/>
  <button onclick="loadJSFile();">Click to load JS</button>
  <br/>
  <button onclick="foo();">call foo()</button>
  <br/>
  <button onclick="unloadJSFile();">Click to unload JS</button>

</body>
</html>

simple.js source:

var foo = function(){
    alert("hello from foo");
}

tshepang

11.7k21 gold badges90 silver badges134 bronze badges

asked Dec 6, 2010 at 9:47

9

This cannot be done.

When a script is executed, function definitions are added to the global window object. There may be debugging symbols attached to the function that indicate where the function came from, but this information is not available to scripts.

About the only way you could achieve something like this would be to create a pseudo-namespace in the script and then throw away that whole namespace when you are done with it. However, this question hints to me that you are trying to do something the wrong way. Perhaps elaborating on your scenario would help us provide alternate solutions.

answered Dec 6, 2010 at 9:52

cdhowiecdhowie

150k23 gold badges278 silver badges290 bronze badges

2

No, that is not possible. You could build a simple cleanup function that removes all variables that were defined in that file:

var foo = 'bar';
var cleanup = function () {
    delete window.foo;
    delete window.cleanup;
};

// unload all resources
cleanup();

Another approach would be to use a modular object structure for your fragments, that clean up after themselves. That involves a slightly higher overhead but is probably worth it, as it makes the code much easier to read and maintain:

// creates the object using the second parameter as prototype.
// .create() is used as constructor
GlobalModuleHandlerThingy.addModule('my_module', {
    create: function () {
        this.foo = 'bar';
        return this;
    },
    foo: null,
    destroy: function () {
        // unload events, etc.
    }
});

GlobalModuleHandlerThingy.getModule('my_module').foo; // => bar
GlobalModuleHandlerThingy.unloadModule('my_module'); // calls .destroy() on the module and removes it.

answered Dec 6, 2010 at 9:51

jwuellerjwueller

30k4 gold badges65 silver badges70 bronze badges

9

perhaps you need to consider conditionally loading it rather than conditionally unloading it...

answered Dec 6, 2010 at 9:50

Cara menggunakan UNLOADS pada JavaScript

RobRob

9,7924 gold badges61 silver badges87 bronze badges

If you need to unload a specific object, it's fairly easy: just set it to {}

ie: myobj = {};

So if you know what objects are created in a particular include, it won't be hard at all.

On the other hand, if you don't know what objects are created in a particular include, there isn't a mechansim to find out - you can't ask Javascript to tell you what was defined in a particular include.

However, I would say that if you don't know what objects are being loaded in a particular javascript file, you're probably not doing yourself any favours in loading it (you should always have a reasonable idea what code does in your site), or in trying to unload it manually (if you don't know what it does, that implies its a third party include, which means that unsetting it manually is likely to break things).

answered Dec 6, 2010 at 10:01

SpudleySpudley

163k39 gold badges229 silver badges304 bronze badges

1

you can make them = null

    function fnc1 (){

    }

    window.fnc1  = null
    //or
    window["fnc1"]  = null

answered Aug 7, 2018 at 15:10

Cara menggunakan UNLOADS pada JavaScript

Was researching for something like that myself and thought I'll post my findings

  1. Wrap your stuff in a global namespace in js file so it can be removed easily, ie var stuff = { blabla: 1, method: function(){} };

  2. When you need to get rid of it, simply set stuff = {}, or null even

  3. Remove script tag from page

*** If you use requirejs - require js remove definition to force reload

Note: as long as you don't reference modules inside the namespace from anywhere else everything will be collected by GC and you are good to go.

answered Aug 5, 2014 at 15:19

Cara menggunakan UNLOADS pada JavaScript

PavdroPavdro

4111 gold badge9 silver badges18 bronze badges

I figured a trick for this. I was wondering here days finding an answer for this and I just realized a perfect trick to do this without trying to unload the java Script. only you have to do is create a global variable like currentPage in your main page's java script and when you loading the page assign the page name to currentPage . then in every other .js file use $('document').ajaxComplete() insted of $('document').ready() add an if statement as first line inside every $('document').ajaxComplete() function. set it to check currentPage variable equals to a new page name. add all other events inside if statement. i don't know English very well so check my code. and This is my first answer here so sorry if i make some mistakes.

main.html

<body>
    <div id='container></div>
    <button id="load1">
    <button id="load1">
</body>

main.js

var currentPage = "";

$(document).ready(function () {
    $('#load1').click(function () {
        loadSource('page1', 'body');
    });
    $('#load2').click(function () {
        loadSource('page2', 'body');
    });
});

function loadSource( page, element){
    currentPage = page;
    $('#container').load('views/' + page + '.php', element);
    $.getScript('js/' + page + '.js');
    $('#css').prop('disabled', true).remove();
    $('head').append('<link rel="stylesheet" href="css/' + page + '.css" type="text/css" />');
}

all of my pages scripts and styles are in seperate folders views, js, css.

page1.html

<body>
    <button id="test1">
    <button id="test2">
</body>

page1.js

$(document).ajaxComplete(function () {
    if(currentPage == 'page1'){
        /*$('#test1').click(function () {
            console.log('page1');
        });*/
        $('#test2').click(function () {
            console.log('page1');
        });
    }
});

page2.html

<body>
    <button id="test1">
    <button id="test2">
</body>

page2.js

$(document).ajaxComplete(function () {
    if(currentPage == 'page2'){
        $('#test1').click(function () {
            console.log('page2');
        });
        /*$('#test2').click(function () {
            console.log('page2');
        });*/
    }
});

i commented one button in each script to check if that button still has old script's affect.

answered Jul 22, 2017 at 10:55

Cara menggunakan UNLOADS pada JavaScript