$(document).ready(function() {
});
$(window).ready(function () {
});
$(window).load(function() {
});
$(window).on('load', function () {
});
$(function() {
});
(function($) {
})(jQuery);
jQuery(document).ready(function ($) {
});
想問一下要用哪個才對?還是有其他更好的?
以及使用的時間點?
另外我發現我把這個拔下來,js代碼還是可以運行...所以是要在什麼樣的情況下才需要使用?
再來就是看哪個最通用?
用這個最好,因為最精簡,其他可以忽略,使用的時間點在於確保html全部load完,
才開始執行js,避免js找不到html dom而發生錯誤,這種寫法等同把js寫在html之後
$(function() {
});
假設我js檔案很多個,每一個都要 $(function(){
嗎?
是的,每個js檔案都是獨立,如果兩個js要使用同一個變數值,就把變數宣告成全域的,就這樣
我記得放在</body>
之前,其他dom元素之後就可以。根元素就是<html>
,放在他之後有點怪,雖然也不會有問題啦。
可以放在之前,是因為dom都已載入了,而且tag只要載入開頭的tag,就算有載入成功,所才才會跟放在html外,使用上沒什麼區別吧
還有一種方式,假設不透過jQuery的方法,或不確定jQuery是否載入
除了IE8外,其他瀏覽器都支持
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
參考資料
https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery
這是許多開發人員常犯的錯誤。 他們使用 $document ready 而不是 $funcion? 因為它寫起來更短,並且適用於所有情況。
描述:事實是! 在 $func 的末尾? 不允許連續調用多個異步函數。 為了連續調用多個異步函數,我們需要使用 jQuery 1.7 中引入的 .waitUntil 方法
那麼,我們如何知道我們的代碼什麼時候會異步執行,什麼時候不會呢? 例如,如果您使用 $(document).ready() 之類的東西,那麼您的代碼總是同步執行,因為不涉及等待。
同步代碼:當代碼按照編寫的順序一行一行執行,並且在執行完畢之前不會暫停或等待任何其他操作時,稱為同步代碼。例如,使用 $(document).ready() 會導致代碼在文檔完全加載後才執行,這是同步的。
異步代碼:當代碼不按照順序執行,而是在某些事件發生或滿足特定條件時執行,drift hunters 並且可能會等待其他操作完成後才執行,稱為異步代碼。例如,使用 $.ajax() 函數發送 AJAX 請求時,代碼將等待服務器響應之前不會阻塞,這是異步的。
VidMate APK is a Free Video Downloader App for Mobile Phones. Download VidMate and Get Free MP3 Music, HD videos from Facebook, Whatsapp & TikTok etc. https://vidmateapps.org/
Insta Pro APK is a modified version of Instagram for Android devices. Instagram Pro allows Users to Download Posts, Stories, Reals and IGTV.
https://instaproapkdownload.net/
Honista is an Instagram Mod Developed by Honista Team. Honista APK Provides Many Features such as Themes, Download Media, Hide Visibility, and Better Privacy. https://honista.cc/
Download the latest version of GBWhatsApp APK Official (Anti Ban). GBWhatsApp APK Download is a popular WhatsApp MOD and an alternative. https://gbplus.app/
CapCut Pro Mod APK removes the limits discovered in the standard version of the application. It unlocks premium features, giving users what they were restricted to experience in the normal version of the application.
Minecraft Pocket Edition used to feel really watered down compared to PC, but the current Minecraft APK is fully featured and feels like the real deal. I’ve built cities, automated farms with redstone, and even played on servers like Lifeboat and Hive right from my phone. Touchscreen controls aren’t for everyone, but there are plenty of customization options to make it more comfortable. Plus, it supports external mods if you’re into that kind of thing, which is a huge plus.https://minecraftapk12.com**/**https://bitlifemodapp.com/
Bitlife Mod APK is a life emulator game where you can play the game several life paths in the digital world. Bitlife Mod APK offers unlocked features.